在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];
Run Code Online (Sandbox Code Playgroud)
我们可以检查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
Run Code Online (Sandbox Code Playgroud)
并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
Run Code Online (Sandbox Code Playgroud)
我不明白为什么设置时结果如此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
Run Code Online (Sandbox Code Playgroud)
正如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.
Run Code Online (Sandbox Code Playgroud)
但是,既然:=是一个赋值运算符,并且j在DT我的范围内进行评估,如果DT[, x.sum:=cumsum(x)]没有赋值给它,那将会很困惑x.sum.
显式括号,即(target):=暗示某种评估,因此语法更清晰.无论如何,在我的脑海里.当然,你也可以paste0直接在左手边打电话等,:=不需要with=FALSE; 例如,
DT[, paste0("SUM.",colNames) := lapply(.SD, ...), by=...]
Run Code Online (Sandbox Code Playgroud)
简而言之,我在使用with时从未使用过:=.
| 归档时间: |
|
| 查看次数: |
204 次 |
| 最近记录: |