【问题标题】:is it possible to negate columns in the by parameter for data.table R是否可以否定 data.table R 的 by 参数中的列
【发布时间】:2017-05-12 14:21:05
【问题描述】:

我想指定总和列并按剩余列分组。似乎没有办法像 .SDcols 那样否定 by 参数中的列。那是对的吗?我找到了另一种方法,但想知道我是否缺少一些 data.table 魔术。

a=data.table(a=c(1,3,1), b=c(2,2,3), c=c(5,6,7))

not_gp = c('b','c')
# this works but is not what I want!
a[,lapply(.SD,sum),by=not_gp,.SDcols =!not_gp]


# what I want, but doesn't work
a[,lapply(.SD,sum),by=!not_gp,.SDcols =not_gp]
# Error in !not_gp : invalid argument type
#does work
gp = names(a)[!names(a) %in% not_gp]
a[,lapply(.SD,sum),by=gp,.SDcols =not_gp]
# also works
a[,lapply(.SD,sum),by=gp]

【问题讨论】:

  • 类似a[, lapply(.SD, sum), by = setdiff(names(a), not_gp), .SDcols = not_gp] 的东西?虽然没有使用数据表魔法:(
  • x[x %in% y]intersect(x,y) 并且,在您编辑之后:x[!x %in% y]setdiff(x,y),如最后评论中所述。
  • @Frank,抱歉我的代码中有错字,所以 setdiff 是我的本意
  • Np,只是让您了解这些功能。可以肯定的是,目前没有比 setdiff 更好的方法了。如果对您有用,您可以要求 UserXYZ 作为答案发布。
  • @User2321 请张贴作为答案....我很惊讶否定不直接支持

标签: r data.table


【解决方案1】:

你可以使用:

a[, lapply(.SD, sum), by = setdiff(names(a), not_gp), .SDcols = not_gp]

这给了你:

   a b  c
1: 1 5 12
2: 3 2  6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 2011-08-14
    • 1970-01-01
    • 2021-05-07
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多