【问题标题】:How to add every row to previous row in a loop R如何在循环R中将​​每一行添加到前一行
【发布时间】:2014-10-03 07:49:21
【问题描述】:

我正在 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)
} 

【问题讨论】:

  • 请考虑提供一些示例数据(也许还有预期的结果)以进行处理。这样做你会得到更多的回应。我可以创建一个示例数据来测试它。但是,它可能无法模仿您拥有的实际数据集。

标签: r for-loop rbind


【解决方案1】:

在您开始 for (id in unique_index) 循环之前,bootresult 中有什么内容? 这部分我不清楚,也许这取决于你如何声明它

对此的替代解决方案是将其声明为

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

并将最后一行替换为

bootresult[id, ] <- bootresult_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-25
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多