根据列的值从其他列获取值

时间:2016-08-23 15:00:15

标签: r if-statement for-loop

对于数据框中的每一行,我想根据第三列中的值将值从一列复制到另一列。

我尝试使用组合for循环和if函数:

Accept: application/vnd.mycompany.tar+pdf

这似乎有用(没有错误信息),但查看我的数据肯定有问题。

例如,第1行有 ## example condition <- c("1","2","2","1","2","","3","3") SZ01 <- c("1","1","1","1","1","","1","1") SZ02 <- c("2","2","2","2","2","","2","2") SZ03 <- c("3","3","3","3","3","","3","3") df <- data.frame(cbind(condition,SZ01,SZ02,SZ03), stringsAsFactors = FALSE) df$retribution <- NULL df$special_prevention <- NULL df$general_prevention <- NULL for (i in 1:length(df$condition)){ if (df$condition[i] == 1){ df$retribution[i] <- df$SZ01[i] df$special_prevention[i] <- df$SZ02[i] df$general_prevention[i] <- df$SZ03[i] }else if (df$condition[i] == 2) { df$retribution[i] <- df$SZ02[i] df$special_prevention[i] <- df$SZ03[i] df$general_prevention[i] <- df$SZ01[i] }else if (df$condition[i] == 3) { df$retribution[i] <- df$SZ03[i] df$special_prevention[i] <- df$SZ01[i] df$general_prevention[i] <- df$SZ02[i] } else { df$retribution[i] <- "missing_condition" df$special_prevention[i] <- "missing_condition" df$general_prevention[i] <- "missing_condition" } } 。这意味着,此行condition == 1的值应与df$retribution的第1行中的值相同。

但事实并非如此。有没有人可以看到我犯的错误?

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

condition <- c("1","2","2","1","2","","3","3")
SZ01 <- c("1","1","1","1","1","","1","1")
SZ02 <- c("2","2","2","2","2","","2","2")
SZ03 <- c("3","3","3","3","3","","3","3")


df <- data.frame(cbind(condition,SZ01,SZ02,SZ03), stringsAsFactors = F)

df$retribution <- ifelse(df$condition == "1", df$SZ01,
                         ifelse(df$condition == "2", df$SZ02,
                            ifelse(df$condition == "3", df$SZ03, "missing")))

df$special_prevention <- ifelse(df$condition == "1", df$SZ02, 
                                ifelse(df$condition == "2", df$SZ03,
                                       ifelse(df$condition == "3", df$SZ01, "missing")))

df$general_prevention <- ifelse(df$condition == "1", df$SZ03, 
                                ifelse(df$condition == "2", df$SZ01,
                                       ifelse(df$condition == "3", df$SZ02, "missing"))))

输出:

df
  condition SZ01 SZ02 SZ03 retribution special_prevention general_prevention
1         1    1    2    3           1                  2                  3
2         2    1    2    3           2                  3                  1
3         2    1    2    3           2                  3                  1
4         1    1    2    3           1                  2                  3
5         2    1    2    3           2                  3                  1
6                              missing            missing            missing
7         3    1    2    3           3                  1                  2
8         3    1    2    3           3                  1                  2