问题描述
ann <- 1:2500
len <- sample(1:3,1000,replace=TRUE)
df <- data.frame(col1= c(1:2500),col2= c(1:2500))
for (i in 1:length(ann)) {
if (length[i]==1) {
df$col1[i] <- len[i] }
else if (length[i]==2) {
df$col1[i] <- len[i]
df$col1[i+1] <- len[i] }
else if (length[i]==3) {
df$col1[i] <- len[i]
df$col1[i+1] <- len[i]
df$col1[i+2] <- len[i] }
}
试图在下一行用数字2重复2的每个实例.而且,如果有3,我希望此后的两行都用数字3.谢谢!我需要练习for循环.
Trying to make every instance of a 2 to be repeated on the following line with the number 2. Also, if there is a 3, I want the two lines following this to have the number 3. Thanks! I need practice with for loops.
Error in if (length[i] == 1) { : missing value where TRUE/FALSE needed
更新:for循环将用以下数字替换每个重复的行,我需要知道如何使2的每个实例之后的i + 1和3的每个实例之后的i + 2.
Update: The for loop will replace every repeated row with the following numbers, I need to know how to make i+1 after every instance of a 2, and i+2 after every instance of a 3.
推荐答案
在这里,我们可以遍历len
的所有元素,并为每个循环做一个内部循环,将len
的元素输入其中. df$col1
的许多行.
Here we can iterate through all the elements of len
, and for each do an inner loop that takes that element of len
and enters it into that many rows of df$col1
.
df_row <- 1
for (i in 1:length(len)) {
for (j in 1:len[i]) {
df[df_row, 1] = len[i]
df_row <- df_row + 1
}
}
这篇关于对于r中的循环问题:if(length [i] == 1){中的错误:缺少需要TRUE/FALSE的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!