【问题标题】:How can I multiply row under certain condition with R? [duplicate]如何在特定条件下将行与 R 相乘? [复制]
【发布时间】:2020-10-04 15:23:01
【问题描述】:

我有一个数据框(又名 df),我想在列满足特定条件时乘以列价格,例如

df$US=='非美国'`.

这是我的代码:

df$Price <- df$Price[df$US=='non US']*0.85

运行上面的代码会导致这个错误:

Error in `$<-.data.frame`(`*tip*`, CompPrice, value = c(140, 114.117647058824,  : 
  replacement has 142 rows, data has 400

我了解错误发生的原因,但是我不知道如何只修改满足条件的行。

提前致谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们需要在&lt;-lhs 上指定逻辑条件,因为 lhs 包含完整的“价格”列

    df$Price[df$US=='non US'] <- df$Price[df$US=='non US']*0.85
    

    通常建议在赋值之前先创建一个对象,避免重复做同样的计算

    i1 <- df$US == 'non US'
    df$Price[i1] <- df$Price[i1] * 0.85
    

    使用data.table,这个语法更简洁

    library(data.table)
    setDT(df)[US == 'non US', Price := Price * 0.85]
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用ifelse...

      df$Price <- ifelse(df$US=='non US', df$Price * .85, df$Price)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-05
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        相关资源
        最近更新 更多