【问题标题】:R: subtract variable amount of columns from target columnR:从目标列中减去可变数量的列
【发布时间】:2023-04-05 18:15:02
【问题描述】:

我希望创建一个接受三个参数的函数:一个 data.table、一个目标列和一个要从目标列中减去的列向量:

test = data.table(
  total = c(10,6,4,4,5,6), 
  b = c(9,5,3,3,4,5), 
  c = rep(1, 6),
  d = rep(2, 6)
)

函数(数据,目标 = “total”,cols = c(“b”,“c”)) 应该给出所需的输出:

test = data.table(
  total = c(10,6,4,4,5,6), 
  b = c(9,5,3,3,4,5), 
  c = rep(1, 6),
  d = rep(2, 6),
  new_total = rep(0, 6)
)

目前的尝试:

1)

testfunction <- function(dt, target, cols){
    dt[, new_total := target - .SD , .SDcols = cols]

}

2)

testfunction <- function(dt, target, cols){
     temp = copy(dt[, .SD, .SDcols = cols])
     dt[, new_total := target - temp]

 }

这些都不起作用,不幸的是,我认为我的尝试表明缺乏对 data.table 的理解。

【问题讨论】:

    标签: r data.table subtraction


    【解决方案1】:

    试试这个:

    foo <- function(data, target = "total", cols = c("b", "c")) {
      data[, new_total := get(target) - rowSums(.SD), .SDcols = cols]
    }
    
    foo(test)[]
    
    #    total b c d new_total
    # 1:    10 9 1 2         0
    # 2:     6 5 1 2         0
    # 3:     4 3 1 2         0
    # 4:     4 3 1 2         0
    # 5:     5 4 1 2         0
    # 6:     6 5 1 2         0
    

    问题是

    1. .SDdata.tabletarget 只是一个向量。

    2. 不能像这样获取带有字符串变量的列,例如,您可以使用get()。更多示例here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多