将值增量保存到R中的数据框

时间:2019-02-07 07:50:13

标签: r

我想从循环到数据框分配值时遇到问题

我尝试使用代码:

output1 <- data.frame(matrix(ncol=1, nrow=10))
colnames(output1) <- "id"
for(i in seq(from=1, to=10, by=1)){
 for(j in seq(from=1, to=2, by=1)){
    output[i,] <- i
    print(paste(i))
  }
}

enter image description here

如果查看print(i)的结果是:

"1"
"1"
"2"
"2"

数据框中的实际结果是

id : "1","2","3"--"10"

enter image description here

请帮助我,谢谢

2 个答案:

答案 0 :(得分:0)

您为什么再次在内部循环播放? for(i in seq(from=1, to=10, by=1)){我将是一个从1到10的连续序列for(j in seq(from=1, to=2, by=1)){ j将只假定1或2,所以:

如果i=1进入第一个循环,而j=1进入output[1,] <- 1 现在j=2output[1,] <- 1

如果要重复第一个值,则第二个赋值应为j值,类似这样

output1 <- data.frame(matrix(ncol=1, nrow=10))
 colnames(output1) <- "id"
 for(i in seq(from=1, to=10, by=2)){
  for(j in seq(from=1, to=2, by=1)){
    output[i,] <- i
    output[i+1,] <- j
    print(paste(i))
  }
}

还有更好的方法来获得结果(如果重复该值是您想要的结果)

output1 <- data.frame(matrix(ncol=1, nrow=10))
 colnames(output1) <- "id"
 for(i in seq(from=1, to=10, by=2)){
    output[i,] <- i
    output[i+1,] <- i+1
    print(paste(i))
}

您也可以参考此问题Sequence of Repeated Values in R

基本上可以告诉您可以使用R中的rep()命令来创建序列中重复值的向量

答案 1 :(得分:0)

如果您要执行的操作是将第一个序列的每个部分两次添加到数据框中,则需要做其他事情。 您的第二个循环仅将第i个数字设置为第i个位置两次。我想将第i个数字设置为第2 * i个和第2 * i + 1个位置?

因此,如果稍微调整一下,亚伦鹦鹉的代码是正确的:

output <- data.frame(matrix(ncol=1, nrow=20))
colnames(output) <- "id"
for(i in seq(from=1, to=10, by=1)){
  output[(2*i)-1,] <- i
  output[(2*i),] <- i
  print(paste(i))
}

这是您要寻找的吗?