首页 > 解决方案 > 对数据表列的子集执行功能并复合分配

问题描述

我有一个包含 3 列的数据表。

> library(data.table)
> library(magrittr)
>
> myDT <- data.table(L = c(1.1,2.2), M = c(3.3, 4.4), R = c(5.5,6.6))
> myDT
     L   M   R
1: 1.1 3.3 5.5
2: 2.2 4.4 6.6

我想要round()2 列。似乎最简单的方法是使用 magrittr 复合赋值运算符%<>%.

> myDT[, c('M', 'R')] %<>% round
> myDT
     L M R
1: 1.1 3 6
2: 2.2 4 7

这很好用,但如果我尝试使用列名向量,它就不起作用。

> toRound <- c('M', 'R')
> myDT[, toRound] %<>% round
Error in `[.data.table`(myDT, , toRound) : 
  j (the 2nd argument inside [...]) is a single symbol but column name 'toRound' is not found. Perhaps you intended DT[, ..toRound]....

包括with = FALSE也会给出错误,即使%<>% round从行中删除在两种情况下都会给出数据表的相同子集。

> myDT[, c('M', 'R')]
     M   R
1: 3.3 5.5
2: 4.4 6.6
> myDT[, toRound, with = FALSE]
     M   R
1: 3.3 5.5
2: 4.4 6.6

使用列名向量时,是否可以在数据表中使用复合赋值运算符?

标签: rdata.tablemagrittr

解决方案


推荐阅读