假设3列为
duration mode fare
34 2 0
20 1 0
15 4 1
10 2 0
3 4 1.3
我需要一个新列,如下所示
If mode=1 is 0
If mode=2 is duration*0.07
If mode=4 is equal fare
输出
duration mode fare cost
34 2 0 34*0.07
20 1 0 0
15 4 1 1
10 2 0 10*0.07
3 4 1.3 1.3
答案 0 :(得分:2)
您可以使用case_when
包中的dplyr
,但是基数R中的常规ifelse
也可以在这里工作:
df$cost <- ifelse(df$mode == 1, 0, ifelse(df$mode == 2, df$duration*0.07, df$fare))
这假设唯一的mode
值为1、2和4,因此存储区else
的条件将仅包括mode = 4
。
答案 1 :(得分:2)
使用在末尾的注解中可重复定义的输入DF
,这里是基数R中的单线。mode == 2
从TRUE / FALSE转换为1/0,对于{{ 1}}。
mode == 4
给予:
transform(DF, cost = (mode == 2) * duration * 0.07 + (mode == 4) * fare)
duration mode fare cost
1 34 2 0.0 2.38
2 20 1 0.0 0.00
3 15 4 1.0 1.00
4 10 2 0.0 0.70
5 3 4 1.3 1.30
答案 2 :(得分:1)
只需将您的条件转换为case_when
中的dplyr
语句
library(dplyr)
df %>%
mutate(cost = case_when(mode == 1 ~0,
mode == 2 ~ duration * 0.07,
mode == 4 ~ fare,
TRUE ~ NA_real_))
# duration mode fare cost
#1 34 2 0.0 2.38
#2 20 1 0.0 0.00
#3 15 4 1.0 1.00
#4 10 2 0.0 0.70
#5 3 4 1.3 1.30
或者嵌套的ifelse
条件
df$cost <- with(df, ifelse(mode == 1, 0,
ifelse(mode == 2, duration * 0.07,
ifelse(mode == 4, fare, NA))))
数据
df <- structure(list(duration = c(34L, 20L, 15L, 10L, 3L), mode = c(2L,
1L, 4L, 2L, 4L), fare = c(0, 0, 1, 0, 1.3)), class = "data.frame",
row.names = c(NA, -5L))