在R中执行for循环

时间:2013-02-26 22:22:55

标签: r for-loop pattern-matching

我对R很新,并且有一些关于我正在尝试执行的循环的问题。我将尝试尽可能最好地解释我希望循环做什么。

for(i in (1988:1999,2000:2006)){
    yearerrors=NULL
    binding=do.call("rbind.fill",x[grep(names(x), pattern ="1988.* 4._ data=")])
    cmeans=lapply(binding[,2:ncol(binding)],mean)
    datcmeans=as.data.frame(cmeans)
    finvec=datcmeans[1,]
    kk=0
    result=RMSE2(yields[(kk+1):(kk+ncol(binding))],finvec)
    kk=kk+ncol(binding)
    yearerrors=c(result)
}

yearerrors
  1. 首先,我希望循环迭代数据的文件名。 特别是1988年至2006年在1988年的地方 现在放在绑定声明中。 x是数据文件列表 输入到R和1988是文件名的一部分。所以我有 文件名以1988,1989,...,2006开头。

  2. yield是一个数值向量,我想输入索引     向量进入函数RMSE2,如循环中所示。对于     例如,在第一次迭代中我希望索引1到     要使用的绑定中的列数。然后进行下一次迭代     我希望第一个索引比前一个迭代多1个     结束并继续使用与下一个绑定中的列数相等的数字     声明。我只是不知道我写的内容是否会完成     此

  3. 最后,我希望将这些结果存储在向量中     yearerrors然后访问此向量。

  4. 提前非常感谢!

1 个答案:

答案 0 :(得分:1)

好的,这里有很多猜测,因为你的数据结构非常不清楚,我不知道RMSE2的功能是什么(你没有给出任何细节)。根据你前几天的问题,我假设你的数据是.csv文件。我要去解决你的问题。

我首先要在读取文件的同时构建合并的数据帧,而不是另一个。像这样:

#Set your working directory to the folder containing the .csv files
#I'm assuming they're all in the form "YEAR.something.csv" based on your pattern matching

filenames <- list.files(".", pattern="*.csv") #if you only want to match a specific year then add it to the pattern match
years <- gsub("([0-9]+).*", "\\1", filenames)

df <- mdply(filenames, read.csv)
df$year <- as.numeric(years[df$X1]) #Adds the year
#Your column mean dataframe didn't work for me
cmeans <- as.data.frame(t(colMeans(df[,2:ncol(df)])))

然后很难知道你想要实现的目标。由于您的datcmeans是一行data.frame,datcmeans[1,]不会改变任何内容。因此,如果数据框(或数字向量)中的一行是RMSE2函数所需的参数,则可以将datcmeans(我的示例中为cmeans)传递给它。

从那时起你的代码对我来说几乎难以辨认。不知道yields是什么样的,或者RMSE2是如何工作的,几乎不可能提供更多帮助。

如果你要在这里做一个循环,我会说在第一次迭代结束时设置kk=kk+ncol(binding)对你没有帮助,因为你设置了kk=0, kk不会等于ncol(binding),这是,我猜,不是你想要的。这是我对你需要的猜测(假设需要循环)。

yearerrors=vector("numeric", ncol(df)) #Create empty vector ahead of loop

for(i in 1:ncol(df)) {
  yearerrors[i] <- RMSE2(yields[i:ncol(df)], finvec)
}
yearerrors

老实说,我无法想象一个可以像这样工作的函数,但它似乎是你的代码最合乎逻辑的适应。