在循环中将数据附加到数据框,但只有最后一个值进入数据框

Append data to data frame in a loops, but only the last value made it into the data frame

我有一个 for loop,& while loop,它在每次迭代后生成一个数据。 我想将所有数据一起添加到一个数据框中,但发现很难。因为只有最后一次循环创建的数据是成功的(可以看下图:output code)。

这是代码,请建议如何修复它:

df = data.frame(matrix(nrow = 350, ncol = 12))
kol<-1
    for (x in 1:350) {
      output  <-  c(paste0(x))
      df[,1] = output 
    }
      while (kol <= 223) {
          if(kol < 224){
            rowd1 <- c(paste("gen ",kol))
          }
          df[,2] = rowd1
          kol = kol+1
        }#while

      while (kol <= 446) {
          if(kol < 447){
            rowd2 <- c(paste("gen ",kol))
          }
        df[,3] = rowd2
          kol = kol+1
      } 
colnames(df) <- c("Kromosom", "A","B","C","D","E","F","G","H","I","J","K")    
df

所以,我会更新我提出的问题。 如果代码变成这样怎么办: 问题:row problem

 ... 
    for (x in 1:350) {
            output  <-  c(paste0(x))
            df[x,1] = output
          }
    for (x2 in 1:223) {
            output2  <-  c(paste("Gen ",x2))
            df[1,2:224] = output2
          }"#why only the value 223 comes out, like the output in the picture 'row problem' that is -Gen 223-"
  ...

对于 data.frame dfdf[,n] 是整个第 n 列。所以你在每一步都设置了整个列。在您的代码中,使用

df[x, 1] = output

例如,为单行设置值。

已解决

特别感谢@JamesHirschorn,非常感谢您帮助解决问题。并感谢提供反馈的人。

待办事项

  • 可能会远离这里 while。为什么不只是用于 反而? – GuedesBF
  • 使用df[x, 1] = output设置第一列中每一行的值

代码

 df = data.frame(matrix(nrow = 350, ncol = 224))
    for (x in 1:350) {
     output  <-  c(paste(x))
     df[x,1] = output
 }
    for (x2 in 2:224) {
     output2  <-  c(paste("Gen ",x2-1))
     df[1,x2] = output2
  }
colnames(df) <- c("Kromosom", "A","B","C","D","E","F","G","H","I","J","K", ...)    
df

输出:here .So,祝我以后好运