这可能是一个愚蠢的问题,但我似乎不明白为什么nrow和length向量的行为不同。
示例:
#Create a dummy data frame
dff = data.frame(X = c(35,18,17,35), Y =c(1,2,3,4))
#Test whether 1:nrow(dff) and 1:length(dff[,1]) are identical
identical(1:nrow(dff), 1:length(dff[,1]))
#[1] TRUE
#Run a nested for-loop
step1 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
for (i in 1:nrow(dff)) {# for each row in the first column
for (j in 1:nrow(dff)) { # for each row in the second column
step1[i, j] <- dff$Y[i] + dff$X[j] # add them in the placeholder
}
}
# [,1] [,2] [,3] [,4]
# [1,] 36 19 18 36
# [2,] 37 20 19 37
# [3,] 38 21 20 38
# [4,] 39 22 21 39
# Now run the same example using 1:length(dff[,1])
step1 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
for (i in 1:length(dff[,1])) {# for each row in the first column
for (j in 1:length(dff[,2])) { # for each row in the second column
step1[i, j] <- dff$Y[i] + dff$X[j] # add them in the placeholder
}
}
# [,1] [,2] [,3] [,4]
# [1,] 0 0 0 0
# [2,] 0 0 0 0
# [3,] 0 0 0 0
# [4,] 0 0 0 0
有什么区别?为什么我得到两个不同的答案,请给出一个虚拟的解释。感谢
答案 0 :(得分:0)
您的第二个for
循环包含step1
变量而不是step2
:D
答案 1 :(得分:0)
您的代码中存在拼写错误:
正如Patronus所说:
step2 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
for (i in 1:length(dff[,1])) {# for each row in the first column
for (j in 1:length(dff[,2])) { # for each row in the second column
step2[i, j] <- dff$Y[i] + dff$X[j] # add them in the placeholder
}
}
# [,1] [,2] [,3] [,4]
# [1,] 36 19 18 36
# [2,] 37 20 19 37
# [3,] 38 21 20 38
# [4,] 39 22 21 39