【问题标题】:In R dataframe, how to change numeric variable in easy way在 R 数据框中,如何以简单的方式更改数值变量
【发布时间】:2021-10-20 10:31:57
【问题描述】:

在 R 数据框中,我想将数值变量更改为相反的数字(乘 -1),其中类别等于“a”或“b”。 目前,代码有点长,还有其他方法吗?谢谢!

test_data <- data.frame(category=c("a","b","x","a","b","c","d"),
           amount_local=c(10,30,52,5,67,5,20),
           amount_usd=c(1,3,5,7,8,3,4))

test_data$amount_local[test_data$category %in% c('a','b') ] <- test_data$amount_local[test_data$category %in% c('a','b') ]*-1

test_data$amount_usd[test_data$category %in% c('a','b') ] <- test_data$amount_usd[test_data$category %in% c('a','b') ]*-1

附加问题:我已经收到了一些对原始问题有用的方法。另外,当我们有两个条件变量作为打击时,“更新代码”无法工作。 @Ronak Shah,你能帮忙吗?谢谢!

test_data_new <- data.frame(
    category=c("a","b","x","a","b","c","d"), sub_category=c("a","b","x","a","b","c","d"), amount_local=c(10,30,52,5,67,5,20),
    amount_usd=c(1,3,5,7,8,3,4))

-----'更新代码'的开始

   ind_new <- test_data_new $category %in% c('a','b') & test_data_new $csub_ategory %in% c('a') 
    
    test_data_new [ind,c(-1,-2)] <- test_data_new [ind, c(-1,-2)] * -1

-----'更新代码'结束

【问题讨论】:

  • 您的附加问题中有一些拼写错误。 1. 数据框名和列名之间不能有空格。所以不是test_data_new $category,而是test_data_new$category。 2.您使用的是csub_ategory,但您的列名是sub_category。 3. 你应该使用ind_new 而不是ind
  • 感谢您的重播!

标签: r dataframe


【解决方案1】:

这行得通吗:

library(dplyr)
test_data %>% mutate(across(starts_with('amount'), ~ ifelse(category %in% c('a','b'), . * -1, .)))
  category amount_local amount_usd
1        a          -10         -1
2        b          -30         -3
3        x           52          5
4        a           -5         -7
5        b          -67         -8
6        c            5          3
7        d           20          4

【讨论】:

    【解决方案2】:

    您可以将多列相乘。为避免重复条件,您可以将其保存在变量中。

    inds <- test_data$category %in% c('a','b')
    test_data[inds, -1] <- test_data[inds, -1] * -1
    
    #  category amount_local amount_usd
    #1        a          -10         -1
    #2        b          -30         -3
    #3        x           52          5
    #4        a           -5         -7
    #5        b          -67         -8
    #6        c            5          3
    #7        d           20          4
    

    【讨论】:

    • 如果我添加条件列,它可以工作。你能帮忙吗?谢谢 ! test_data
    • 抱歉,有什么问题吗?您尝试过的(在上面的评论中)有效并且是正确的。 @anderwyang
    • 你能帮我解决我的“其他问题”吗(我编辑了我的问题并添加了更多内容)。谢谢!
    【解决方案3】:

    如果条件相同,可以一次选择多列。

    test_data[test_data$category %in% c('a','b'), c('amount_local', 'amount_usd')] <- test_data[test_data$category %in% c('a','b'), c('amount_local', 'amount_usd')] * -1
    

    还有很多 dplyr 解决方案,如果您稍微阅读一下,应该会很清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多