R

时间:2018-03-30 02:14:26

标签: r if-statement

“if语句后的多个动作” 有没有办法让它变得简单?
数据帧异常包含多个cols,包括Lab,v1,v2,v3,v4,v5,v6; 我想做的是如果Lab ==“2018AV”,那么我想要分配v1 =“20x3”,v2 =“7x3”,v3 =“8x3”......这意味着只有这一行会改变。

if (abnormal$Lab in c("2018AV")) {abnormal$v1="20x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v2="7x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v3="8x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v4=NA}
if (abnormal$Lab in c("2018AV")) {abnormal$v5=NA}
if (abnormal$Lab in c("2018AV")) {abnormal$v6=NA}

1 个答案:

答案 0 :(得分:1)

你的问题有点模糊。这是你想要的吗?

for (i in 1:nrow(abnormal)){
    if (abnormal$Lab[i] == "2018AV"){
        abnormal$v1[i] = "20x3"
        abnormal$v2[i] = "7x3"
        abnormal$v3[i] = "8x3"
        abnormal$v4[i] = NA
        abnormal$v5[i] = NA
        abnormal$v6[i] = NA
    }
}

或假设您要更新数据框中的所有列...

if ("2018AV" %in% abnormal$Lab) {
    abnormal[abnormal$Lab == "2018AV",] <- 
                                     c("2018AV", "20x3", "7x3", "8x3", NA, NA, NA)
}