Get value from other column based on value of a column

后端 未结 1 424
一整个雨季
一整个雨季 2021-01-28 21:29

For each row in a data frame I want to copy a value from one column to another depending on a value in third column.

I tried to do it with a combined for loop and if fun

相关标签:
1条回答
  • 2021-01-28 22:07

    Try the following:

    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"))))
    

    Output:

    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
    
    0 讨论(0)
提交回复
热议问题