使用for循环在if else条件下创建向量

时间:2018-10-21 18:17:49

标签: r

如何将下面的for循环的3项输出转换为数据框。在尝试解决方案时,我尝试过:

-创建与for循环相关的对象,但无法成功 -创建矩阵,没有效果

什么代码会将输出转换为向量或列表?

> for(i in X$Planned)ifelse(is.na(i),print("ISNA"),print("NOTNA"))
[1] "NOTNA"
[1] "NOTNA"
[1] "ISNA"

1 个答案:

答案 0 :(得分:1)

sapply(x$Planned, function(elem) if (is.na(elem)) {"isNA"} else {"notNA"})

# this will do it!

# however, it will be slower than the vectorized form

ifelse(is.na(x$Planned), "isNA", "notNA")