【问题标题】:Use data.table to change columns' values使用 data.table 更改列的值
【发布时间】:2021-06-14 08:13:01
【问题描述】:

我有一个数据集 dft 由变量 nameweightheight 组成,如下所示

name <- c("Bob","Mary","Jane","Kim")
weight <- c(60,65,45,55)
height <- c(170,165,140,135)
dft <- data.table(name,weight,height,) 

现在对于Bob,我想将其重量加 10,将其高度加 12。我试过这个:

dft[, c("weight","height") := lapply( .SD,  function(x){  
                             if (x == c(60,170) ) {
                                x = c(70,182)
                             }
                                  }), .SDcols = grep("eight$",names(dft)) ]

但它不起作用。警告和错误一再出现。我希望使用lapply 来做到这一点。任何建议表示赞赏。

【问题讨论】:

  • 这对你有用吗?我有点不清楚你为什么要使用lapplydft[name=="Bob", c("weight", "height") := .(weight + 10, height+12)]

标签: r dplyr data.table tidyverse


【解决方案1】:

我们可以使用fifelseMap(假设我们匹配的值)

library(data.table)
dft[, c("weight","height") := Map(function(x, y) 
    fifelse(x %in% c(60, 170), x + y, x), .SD, c(10, 12)),
      .SDcols =  patterns('eight$')][]

-输出

#    name weight height
#1:  Bob     70    182
#2: Mary     65    165
#3: Jane     45    140
#4:  Kim     55    135

或者如果是基于'name'的值

dft[name == 'Bob', c('weight', 'height') :=
       .SD + list(10, 12), .SDcols = patterns("eight$")]

数据

dft <- data.table(name,weight,height) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多