例如,如果col 2中的值为“MED”,则在新col3中,应为其分配1。 如果col 2中的值为“PAT”,则在col3中,它显示为2.
答案 0 :(得分:0)
执行此操作的简便方法是使用mutate
函数中的case_when
和dplyr
函数:
df <- df %>%
mutate(col3 = case_when(
col2 == 'MED' ~ 1,
col2 == 'PAT' ~ 2))
这会在df
中创建一个名为col3
的新列,当该行1
和col2
的值为== 'MED'
时,其值为2
当col2 == '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)