2014-01-26 31 views
-1

我创建了一个循环,通过一组文件进行迭代,并指定在文件中的数据给一个变量对象未找到[R

for(i in 1:8){ 
    infile <-paste("coauthor", i,".csv",sep="") 
    coa[i]<-read.csv(infile,header = TRUE, sep="\t") 
} 

然而,我不断收到错误交替

Error in read.table(file = file, header = header, sep = sep, quote = quote, : 
    object 'infile' not found 

并更频繁地

Error in paste("coauthor", i, ".csv", sep = "") : object 'i' not found 

我在这里错过了什么?

+0

你的文件存储在哪里,'getwd()'的输出是什么? – Fernando

+0

对不起,在执行此命令之前,我将wd设置为正确的位置,就像'setwd(“D:/ n4jbatch”) getwd()'用getwd()生成正确的wd –

+0

您会得到两个非常不同的错误,我认为需要更多的信息来解决这个问题。 – Fernando

回答

2

首先,不需要for循环。其次,如果你这样做,你需要预先定义coa。第三,您必须适当地使用setwd(...)read.csv(...)才能找到这些文件。

setwd("<directory with coauther files...>") 
# this just creates a bunch of files so we can read them back in... 
df <- data.frame(x=1:3, y=4:6, z=7:9) 
lapply(1:5, function(i)write.csv(df,paste0("coauthor",i,".csv"))) 

# this is the code that reads them in. This is all you need. 
coa <- lapply(1:5, function(i)read.csv(paste0("coauthor",i,".csv"))) 

注意coa现在是具有5个元素,每个包含的文件中的一个的内容的列表。

coa[1] 
# [[1]] 
# X x y z 
# 1 1 1 4 7 
# 2 2 2 5 8 
# 3 3 3 6 9 
+0

我将预先分配更改为预定义。声明“不需要”意味着循环不是必需的,这是绝对正确的。 – jlhoward

+0

'不需要'的好处 –

+0

在这个特定的实例中,我想从文件中读取数据到数据框中,对数据框执行一些修改,然后将修改后的框架绑定到现有的数据框上。您对预定义的回答确实有帮助,您的解决方案可能适用于我的更广泛的问题,但我无法说清楚。 –