【发布时间】:2016-12-29 09:52:57
【问题描述】:
我正在测试 R,但遇到了一个问题。如何像在 Excel 中一样在 r 中锁定行 [单元格]。
示例:数据集(dff)
X Y
35 1
18 2
17 3
35 4
我想做一个嵌套的 for 循环,我想用 1 添加 35,然后添加 2、3 和 4。一旦这结束了,我将添加 18 和 1、2、3、4 等
为此,我需要分两步完成:
第 1 步: 创建一个存储嵌套 for 循环的矩阵
结果应该是这样的
X V1 V2 V3 V4
35 36 19 18 36
18 37 20 19 37
17 38 21 20 38
35 39 22 21 39
每次我只是简单地将 X 行与 Y 行相加
为此,我编写了这个嵌套的for循环
step1 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
for (i in 1:nrow(dff[,1])) # for each row in the first column
for (j in 1:nrow(dff[,2])){ # for each row in the second column
add[i,j] = i +j # add them in the placeholder
}
问题: 我收到一条错误消息:
Error in 1:nrow(dff[, 1]) : argument of length 0
步骤 2:将步骤 1 列的总和添加到我的原始数据集(dff)
dff <- cbind(dff, apply(add[,-1], 2,sum) # calculate the column sums of all except the X column, where 2 is refering to column
请更正我的嵌套 for 循环,然后提供其他方法,否则我将永远学不会:) 谢谢
【问题讨论】: