在data.table
默认情况下with = TRUE
和j
被评估在框架内的x
。这样有助于将列名用作变量。当时with = FALSE
,j
是要选择的名称或位置的向量。
我设法找到了一些示例with = FALSE
。
set.seed(1234)
DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))
## The askers's solution
#first step is to create cumsum columns
colNames <- c("x","v"); newColNames <- paste0("SUM.",colNames)
DT[, newColNames := lapply(.SD,cumsum) ,by=y, .SDcols = colNames, with=FALSE];
test <- DT[, newColNames:=lapply(.SD,cumsum) ,by=y, .SDcols=colNames, with=TRUE];
我们可以检查一下DT
:
> DT # setting `with=FALSE` - what I require
x y v SUM.x SUM.v
1: 1 A 12 1 12
2: 1 B 62 1 62
3: 1 A 60 2 72
4: 1 B 61 2 123
5: 2 A 83 4 155
6: 2 B 97 4 220
7: 2 A 1 6 156
8: 2 B 22 6 242
9: 3 A 99 9 255
10: 3 B 47 9 289
11: 3 A 63 12 318
12: 3 B 49 12 338
并且test
是:
> test # this is when setting " with = TRUE"
x y v newColNames
1: 1 A 12 1
2: 1 B 62 1
3: 1 A 60 2
4: 1 B 61 2
5: 2 A 83 4
6: 2 B 97 4
7: 2 A 1 6
8: 2 B 22 6
9: 3 A 99 9
10: 3 B 47 9
11: 3 A 63 12
12: 3 B 49 12
我不明白为什么设置时结果是这样with = TRUE
。所以我的问题基本上是什么时候with = TRUE
有用?
我不明白为什么默认设置是with = TRUE
,尽管一定有很好的理由。
非常感谢!
我明白你的意思了。我们已不再使用with=TRUE|FALSE
与结合使用:=
。由于尚不清楚是with=TRUE
指的左侧还是右侧:=
。取而代之的:=
是,现在最好将LHS的方括号括起来。
DT[, x.sum:=cumsum(x)] # assign cumsum(x) to the column called "x.sum"
DT[, (target):=cumsum(x)] # assign to the name contained in target's value
正如贾斯汀(Justin)提到的,大多数时候,我们分配给我们预先知道的新的或现有的列。换句话说,最常见的是,分配给它的列不保存在变量中。我们做了很多,所以需要方便。也就是说,它data.table
很灵活,还允许您以编程方式定义目标列名称。
我想可以这样认为:
DT[, "x.sum":=cumsum(x)] # assign cumsum(x) to the column called "x.sum"
DT[, x.sum:=cumsum(x)] # assign to the name contained in x.sum's contents.
但是,由于:=
是赋值运算符,并且j
在的范围内进行求值DT
,所以如果DT[, x.sum:=cumsum(x)]
不分配给该x.sum
列,将会造成混乱。
显式括号(即(target):=
)表示某种求值方式,因此语法更加清晰。反正在我心中。当然,你可以调用paste0
在左侧直接等:=
也无需with=FALSE
; 例如,
DT[, paste0("SUM.",colNames) := lapply(.SD, ...), by=...]
简而言之,with
当我使用时,我从不使用:=
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句