If语句-条件长度大于1
问题描述:
我有两列( df $ Z
和 df $ A
)
我基本上要说:如果df $ Z小于5,则用 NA
填充 df $ A
,如果没有,则保留 df $一个
.我已经尝试了这些方法,但是不确定哪里出了问题或错误消息表示什么.
I basically want to say: if df$Z is less than 5, then fill df$A
with an NA
and if not then leave df$A
alone. I've tried these things but am not sure where I'm going wrong or what the error message means.
if(df$X<5){df$A <- NA}
错误:
如果if(df $ X< 5){:条件的长度> 1,并且仅使用第一个元素
In if (df$X < 5) { : the condition has length > 1 and only the first element will be used
我也尝试做更多类似的事情.
I also tried to do something more like this.
for(i in dfX){
if(df$X<5){
df$A <- "NA"
}
}
答
如果需要声明,则为否.这就是矢量化的魔力.
No if statement needed. That's the magic of vectorization.
df$A[df$Z < 5] <- NA