Create new column based on 4 values in another column

后端 未结 4 711
生来不讨喜
生来不讨喜 2020-12-05 02:25

I want to create a new column based on 4 values in another column.

if col1=1 then col2= G;
if col1=2 then col2=H;
if col1=3 then col2=J;
if col1=4 then col2=         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-05 02:48

    There are a number of ways of doing this, but here's one.

    set.seed(357)
    mydf <- data.frame(col1 = sample(1:4, 10, replace = TRUE))
    mydf$col2 <- rep(NA, nrow(mydf))
    mydf[mydf$col1 == 1, ][, "col2"] <- "A"
    mydf[mydf$col1 == 2, ][, "col2"] <- "B"
    mydf[mydf$col1 == 3, ][, "col2"] <- "C"
    mydf[mydf$col1 == 4, ][, "col2"] <- "D"
    
       col1 col2
    1     1    A
    2     1    A
    3     2    B
    4     1    A
    5     3    C
    6     2    B
    7     4    D
    8     3    C
    9     4    D
    10    4    D
    

    Here's one using car's recode.

    library(car)
    mydf$col3 <- recode(mydf$col1, "1" = 'A', "2" = 'B', "3" = 'C', "4" = 'D')
    

    One more from this question:

    mydf$col4 <- c("A", "B", "C", "D")[mydf$col1]
    

提交回复
热议问题