【问题标题】:reading csv and create row -1 as value in new column读取 csv 并在新列中创建行 -1 作为值
【发布时间】:2018-03-16 11:36:04
【问题描述】:

我有一组 csv 文件,其中包含所有文件中相同格式的数据。 格式如下

CA.csv  -- 

row:1- jones            
row:2- May          
row:3-
row:4- Date_transaction cards_hold  status  amount
row:5- 5/25/2018 3:15      2            Active  233
row:6- 5/25/2018 3:30      2            Active  4534

 NY.csv  --
row:1- gary         
row:2- May          
row:3-
row:4- Date_transaction cards_hold  status  amount
row:5- 5/25/2018 5:00      2            Active  565
row:6- 5/25/2018 6:30      2            Active  533   

上述格式对所有其他 csv 文件重复

o/p (i.e name is in first row in csv file should read and create as value in "name" column)
Date_transaction    cards_hold  status  amount  name
5/25/2018 3:15     2            Active  233     jones
5/25/2018 3:30     2            Active  4534    jones
5/25/2018 5:00     2            Active  565     gary
5/25/2018 6:30     2            Active  533     gary

我已尝试使用以下代码。

 files <- dir("RawData", recursive=TRUE, full.names=TRUE, pattern="\\.csv$")
   raw = rbindlist(lapply(files, fread))

【问题讨论】:

  • 你能再描述一下你的问题吗?顺便说一句,您的第二个代码框中的 csv 有一列名为“名称,另一个不是。我以为您是在告诉我们它们是相同的?
  • 第二个代码框是需要的o/p,它在所有csv文件中附加第6行的所有行,并从所有csv文件的第1行创建新列“名称”,第4行作为列名。所有 csv 文件的格式都相同
  • 您的文件的实际外观如何?文件名是文件的一部分吗?这是row:x- 文件的一部分吗?每个文件是否只有两条记录,或者有多少条记录?什么是字段分隔符 - 你称它为 CSV,但我看到的是空格,或者它们是制表符?

标签: r csv


【解决方案1】:
setwd("directory_path_of_your_csv_files/")
file_lst <- list.files(".")

read_all_csv <- function(f_name){
  csv_data <- read.csv(f_name, header=T, stringsAsFactors=F, skip=3)
  name <- read.csv(f_name, header=F, nrows=1)$V1
  csv_data$name <- rep(name, nrow(csv_data))
  csv_data
}

df <- Reduce(rbind, lapply(file_lst, function(x) read_all_csv(x)))

【讨论】:

  • 感谢@prem,我使用了 df
猜你喜欢
  • 2021-05-08
  • 2018-09-23
  • 2017-11-02
  • 1970-01-01
  • 2021-11-04
  • 2017-08-07
  • 1970-01-01
  • 2019-05-01
  • 2018-02-01
相关资源
最近更新 更多