读取 .csv 文件列表,然后将它们绑定在一起而不删除任何列
Reading in a list of .csv files and then binding them together without dropping any columns
我想创建一个包含多个 .csv 文件的数据框而不丢失任何列(即对于任何没有特定列的 .csv,space 将填充 NA
。我希望此过程按列名对齐它们,但 .csv 中的列顺序也不总是匹配。
我从一个只有上述文件的文件夹中创建了一个 .csv 文件列表
files <- dir("C:/...")
我想将这些 .csv 文件读入一个数据框中。到目前为止我得到了什么...
table_all <- do.call(rbind.fill(ldply(files, read.csv,
stringsAsFactors= TRUE, header= T, sep= ",")))
我假设解决方案涉及 do.call
和 rbind
、bind_rows
或 rbind.fill
的某种组合。我读过一些关于 rbindlist
计算更轻的内容,但它只按位置匹配,并且由于我的 .csv 的列顺序不正确,我需要一些按名称匹配的内容。
解决这个问题的一般方法需要一些步骤。请参阅下面的伪代码(直到我们更好地处理您的特定示例):
# step 1 -- list files and prepare columns
file_list <- list.files(path="your_path",
pattern="your_pattern",
full.names=TRUE)
all_columns <- c("list", "your", "columns", "here")
# ideally all_columns will come from names(df)
# with df being your most complete df
# step 2 -- read and match columns before binding
li <- purrr::map(file_list,
function(file){
df <- read.csv(file)
current_names <- names(df)
# find what names are missing
# do mutate(missing_names = NA)
return(df)
}
)
# step 3 -- bind
output <- bind_rows(li)
我想创建一个包含多个 .csv 文件的数据框而不丢失任何列(即对于任何没有特定列的 .csv,space 将填充 NA
。我希望此过程按列名对齐它们,但 .csv 中的列顺序也不总是匹配。
我从一个只有上述文件的文件夹中创建了一个 .csv 文件列表
files <- dir("C:/...")
我想将这些 .csv 文件读入一个数据框中。到目前为止我得到了什么...
table_all <- do.call(rbind.fill(ldply(files, read.csv,
stringsAsFactors= TRUE, header= T, sep= ",")))
我假设解决方案涉及 do.call
和 rbind
、bind_rows
或 rbind.fill
的某种组合。我读过一些关于 rbindlist
计算更轻的内容,但它只按位置匹配,并且由于我的 .csv 的列顺序不正确,我需要一些按名称匹配的内容。
解决这个问题的一般方法需要一些步骤。请参阅下面的伪代码(直到我们更好地处理您的特定示例):
# step 1 -- list files and prepare columns
file_list <- list.files(path="your_path",
pattern="your_pattern",
full.names=TRUE)
all_columns <- c("list", "your", "columns", "here")
# ideally all_columns will come from names(df)
# with df being your most complete df
# step 2 -- read and match columns before binding
li <- purrr::map(file_list,
function(file){
df <- read.csv(file)
current_names <- names(df)
# find what names are missing
# do mutate(missing_names = NA)
return(df)
}
)
# step 3 -- bind
output <- bind_rows(li)