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

使用dplyr根据另一列中的值添加新列,r,dplyr,R,Dplyr,我有一列数据框df$c_touch: c_touch 0 1 3 2 3 4 5 其中,每个数字指的是一段持续时间,0=2分钟,1=5分钟,2=10分钟,3=15分钟,4=20分钟,5=30分钟 我想添加另一列df$c_duration如下 c_touch c_duration 0 2 1 5 3 15 2 10 3 15 4 20 5 30 到目前为止,我一直在使用一个循环,它有点难看/混乱,我宁愿不使用它。是否有一种无循环的方式来添加中的额外列,特别是使用dplyr mutate函数(因

我有一列数据框
df$c_touch

c_touch
0
1
3
2
3
4
5
其中,每个数字指的是一段持续时间,
0=2分钟,1=5分钟,2=10分钟,3=15分钟,4=20分钟,5=30分钟

我想添加另一列
df$c_duration
如下

c_touch c_duration
0 2
1 5
3 15
2 10
3 15
4 20
5 30

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

这里有一个
dplyr
解决方案:

# data.frame containing the mapping
map <- data.frame(
    idx = 0:5,
    val = c(2, 5, 10, 15, 20, 30))

# Sample data   
df <- read.table(text =
    "c_touch
0
1
3
2
3
4
5", header = T)

dplyr::left_join(df, map, by = c("c_touch" = "idx"))
#  c_touch val
#1       0   2
#2       1   5
#3       3  15
#4       2  10
#5       3  15
#6       4  20
#7       5  30
#包含映射的data.frame

map当内部发生变异时,可以使用dplyr::case\u:

df <- df %>%
    mutate(c_duration = case_when(c_touch == 0 ~ 2,
        c_touch == 1 ~ 5,
        c_touch == 2 ~ 10,
        c_touch == 3 ~ 15,
        c_touch == 4 ~ 20,
        c_touch == 5 ~ 30))
df%
当(c_touch==0~2时,突变(c_持续时间=案例),
c_touch==1~5,
c_touch==2~10,
c_touch==3~15,
c_touch==4~20,
c_touch==5~30)

持续时间是否有模式?或者这就是c_接触的程度。i、 e.5分钟后是否有额外的持续时间?是的。只需将您的data.frame和一个lookup data.frame(查找data.frame,将CU触控映射到CU持续时间)合并即可。您可以使用base R或dplyr或data.table或…创建一个命名的参考向量并进行匹配,例如
x
df %>%
 mutate(c_duration = case_when(
 c_touch == 0 ~ 2,
 c_touch == 5 ~ 30,
 T ~ c_touch * 5))