如何将每一行添加到循环R中的上一行

时间:2014-10-02 22:53:32

标签: r for-loop rbind

我在r中写了一个循环,错误信息来自最后一行:   " match.names(clabs,names(xi))出错:   名称与以前的名称不匹配" 最后一行试图保留每个循环的每一行值。感谢大家。

a = 20 # resample times
for (id in unique_index){

  jeep_id <- jeep_boot[which(jeep$index == id),]

  #sample_size is 0.8 of the whole data
  sample_size <- floor((0.8)*length(jeep_id$PR))

  #bootstrap sample means 
  samplemeans = rep(NA, a)

  for (i in 1:a) {

    bootsample.i = sample(jeep_id$PR, sample_size, replace=T)
    samplemeans[i] = mean(bootsample.i)

  }
  #combine mean of 20 sample means and stand dieviation of sample means to be one row
  bootresult_id <- cbind(id, mean(samplemeans), sd(samplemeans))
  #retain every row value for each round looping 
  bootresult <- rbind(bootresult, bootresult_id)
} 

1 个答案:

答案 0 :(得分:0)

开始bootresult循环之前for (id in unique_index)中的内容是什么? 这部分对我来说并不清楚,也许这取决于你如何在第一时间宣布它

Alternativo解决方案将其声明为

bootresult <- matrix(nrow = length(unique_index), ncol=3)

并用

替换最后一行
bootresult[id, ] <- bootresult_id