【问题标题】:Take difference between variables to create new variable unless they match取变量之间的差异来创建新变量,除非它们匹配
【发布时间】:2018-10-07 03:02:17
【问题描述】:
test <- data.frame('cost'= c(120, 3, 2, 4, 10, 110, 200, 43, 1, 51, 22, 14),
               'price' = c(120, 20, 10, 4, 3, 4, 30, 43, 56, 88, 75, 44)
                )
test

    > test
   cost price
1   120   120
2     3    20
3     2    10
4     4     4
5    10     3
6   110     4
7   200    30
8    43    43
9     1    56
10   51    88
11   22    75
12   14    44

我正在尝试创建一个新变量来获取两列之间的差异,除非它们匹配,如果它们匹配,那么它将返回两列都具有的值。

Desired:
   cost price NewVar
1   120   120   120
2     3    20   -17
3     2    10   -8
4     4     4    4
5    10     3    7
6   110     4   106
7   200    30   170
8    43    43    43
9     1    56   -55
10   51    88   -37
11   22    75   -53
12   14    44   -30

这是我尝试过的,但它给了我一个错误,我错过了一个 TRUE/FALSE 参数或类似的东西。

test <- test %>%
        mutate(NewVar = if(cost==price) cost else cost - price)

谢谢!

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    我们可以使用ifelse 代替if/else,因为if/else 没有向量化,需要一个长度为1 的向量。这里的行数大于1,所以使用向量化的ifelse 或@987654325 @(来自dplyr,它还检查type)或case_when

    test$NewVar <- with(test, ifelse(cost == price, price, cost - price))
    test$NewVar
    #[1] 120 -17  -8   4   7 106 170  43 -55 -37 -53 -30
    

    或使用dplyr

    library(dplyr)
    test %>%
         mutate(NewVar = ifelse(cost == price, price, cost - price))
    

    case_when

    test %>%
         mutate(NewVar = case_when(cost == price ~ price,
                          TRUE ~ cost -price))
    

    【讨论】:

    • 非常感谢您的宝贵时间!当你在脑海中读到“~”时,我有个小问题,你怎么看?
    • @KreitzGigs 谢谢。我想它伴随着实践,即使用特定功能会期望特定输出。
    猜你喜欢
    • 2021-11-27
    • 2020-02-18
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2019-06-25
    • 2018-04-02
    相关资源
    最近更新 更多