使用 dplyr 根据另一列中的值添加新列

sah*_*ahn 2 r dplyr

我有一列数据框df$c_touch

c_touch
0
1
3
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

其中每个数字指的是一段时间,使得0 = 2 mins, 1 = 5 mins, 2 = 10 mins, 3=15 mins, 4=20 mins, 5=30 mins.

我想添加另一列,df$c_duration就像

c_touch c_duration
0 2
1 5
3 15
2 10
3 15
4 20
5 30
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直在使用循环,这有点丑陋/混乱,我宁愿不使用它。是否有一种无循环的方法来添加额外的列,特别是使用 dplyr mutate 函数(因为我正在尝试使用 dplyr 重写所有代码)?

Vin*_*lix 7

library(dplyr)

df %>%
  mutate(
    c_duration = case_when(
      c_touch == 0 ~ 2,
      c_touch == 5 ~ 30,
      TRUE ~ c_touch * 5
    )
  )
Run Code Online (Sandbox Code Playgroud)