用3列制作一个新列

时间:2019-09-01 14:38:03

标签: r dataframe

假设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

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))