使用以下代码,我正在将多个csv文件读取到数据帧中。
/* If the browser window is smaller than 600px, make the columns stack on top of each other */
@media only screen and (max-width: 600px) {
.col {
display: block;
width: 100%;
}
}
当我尝试通过以下代码访问它们
setwd("/path/to/files")
filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))
for(i in filenames){
assign(i, read.csv(paste(i, ".csv", sep="")))
}
我收到以下错误
for (i in filenames) {
imanDavenportTest(i)
}
有人可以帮我吗?
答案 0 :(得分:2)
您的“文件名”只是代表从read.csv
导入的数据名称的字符串。您需要get
从这些命名对象中获取数据。
所以尝试:
for(i in filenames){
imanDavenportTest(get(i))
}
答案 1 :(得分:2)
爱德华的答案是正确的。但是我想在您进行操作时以一种非常复杂的方式添加注释,而没有充分利用R。
这里没有理由使用assign
。您可以一次性读取所有数据,并将结果存储为单个对象(列表),而不用N
个对象污染您的工作空间。例如:
# read files in your directory
file_ls <- list.files('.', pattern=".csv$")
# use lapply to read each file and create a list of data frames
data_ls <- lapply(file_ls, read.csv)
# perform the test on each element of the list
lapply(data_ls, imanDavenportTest)
assign
通常被来自具有全局变量的语言的人们采用,但是它没有利用R的面向对象的函数编程的优势。恕我直言,以这种方式使用assign
会创建难以阅读且难以维护的代码。