【发布时间】:2018-03-14 10:52:01
【问题描述】:
(我知道 for 循环不是 R 中的首选,但这是我能想到的最好的选择)
我正在尝试遍历向量并在满足条件后返回向量值。
一旦满足下一个条件,我想删除该变量。
到目前为止,我已经了解了以下内容:
df = c(1:10)
sig = function (df) {
pos = integer(10)
for (i in 1:10) {
if (df[i] > 3 ) { # Once df[i] is bigger than 3 store the value of df[i]
pos[i] = df[i]
}
else if(df[i] < 7 ){ # Keep value of df[i] until next condition is met
pos[i] = pos[i - 1]
}
else{pos[i] = 0} # set the value back to 0
}
reclass(pos,df)
}
sig(df)
我收到以下错误Error in pos[i] <- pos[i - 1] : replacement has length zero
答案应如下所示:
df sig
1 0
2 0
3 0
4 4
5 4
6 4
7 0
8 0
9 0
10 0
有什么想法吗?
【问题讨论】: