为什么rbind需要一个循环来创建一个数据帧而不仅仅是一个矩阵向量

时间:2022-09-25 04:17:40
for (i in 1:5) {
        dat <- rbind(dat, read.csv(files_full[i]))

works, but

工作,但

dat <- rbind(dat, read.csv(files_full[1:5]))

doesn't:

不会:

Error in file(file, "rt") : invalid 'description' argument

文件错误(文件,“rt”):无效的'description'参数

files_full returns this:

files_full返回:

[1] "diet_data/Andy.csv"  "diet_data/David.csv" "diet_data/John.csv" 
[4] "diet_data/Mike.csv"  "diet_data/Steve.csv"

from this exercise: https://github.com/rdpeng/practice_assignment/blob/master/practice_assignment.rmd

从这个练习:https://github.com/rdpeng/practice_assignment/blob/master/practice_assignment.rmd

1 个解决方案

#1


1  

rbind() is meant to bind all it's parameters, not elements contained in lists inside of its parameters. For example

rbind()用于绑定其所有参数,而不是绑定在其参数内的列表中的元素。例如

dat <- rbind(read.csv(files_full[1]), read.csv(files_full[2], read.csv(files_full[3])

would work. If you want to turn a list into parameter, you use do.call

会工作。如果要将列表转换为参数,请使用do.call

dat <- do.call("rbind", Vectorize(read.csv, SIMPLIFY = FALSE)(files_full))

Here I used Vectorize() to allow read.csv to return a list when given a vector of file names.

在这里,我使用Vectorize()来允许read.csv在给定文件名向量时返回一个列表。

#1


1  

rbind() is meant to bind all it's parameters, not elements contained in lists inside of its parameters. For example

rbind()用于绑定其所有参数,而不是绑定在其参数内的列表中的元素。例如

dat <- rbind(read.csv(files_full[1]), read.csv(files_full[2], read.csv(files_full[3])

would work. If you want to turn a list into parameter, you use do.call

会工作。如果要将列表转换为参数,请使用do.call

dat <- do.call("rbind", Vectorize(read.csv, SIMPLIFY = FALSE)(files_full))

Here I used Vectorize() to allow read.csv to return a list when given a vector of file names.

在这里,我使用Vectorize()来允许read.csv在给定文件名向量时返回一个列表。