我想创建一个新列,将前一列中的值设置为R中的其他值

时间:2018-04-17 20:19:56

标签: r

例如,如果col 2中的值为“MED”,则在新col3中,应为其分配1。 如果col 2中的值为“PAT”,则在col3中,它显示为2.

2 个答案:

答案 0 :(得分:0)

执行此操作的简便方法是使用mutate函数中的case_whendplyr函数:

df <- df %>%
    mutate(col3 = case_when(
               col2 == 'MED' ~ 1,
               col2 == 'PAT' ~ 2))

这会在df中创建一个名为col3的新列,当该行1col2的值为== 'MED'时,其值为2col2 == 'PAT'

答案 1 :(得分:0)

使用ifelse()是实现此目标的快捷方法:

df <- data.frame('col_2' = c('MED', 'MED', 'PAT', 'PAT'))

df$col_3 <- c()

df$col_3 <- ifelse(df$col_2 == 'MED', 1, 2)