我正在尝试将以下 dplyr 代码转换为data.table等效代码。
但是,data.table,但不是 dplyr ,给了我错误
Error: k <= n is not TRUE
。
#using dplyr
library(dplyr)
library(zoo) #rollmean function
DF<-mtcars
DF %>%
filter(cyl==6)%>%
group_by(am,vs) %>%
mutate(cumsum_mpg=cumsum(mpg),cummin_disp=cummin(disp),rollmean_wt=rollmean(wt,k=2,fill=0,align="right"))
#using data.table
library(data.table)
library(zoo) #rollmean function
DT<-data.table(mtcars)
setkey(DT,am,vs)
mynames<-c("cumsum_mpg","cummin_disp","rollmean_wt")
DT[,.SD[cyl==6] [,eval(mynames):=list(cumsum(mpg),cummin(disp),rollmean(wt,k=2,fill=0,align="right"))],by=.(am,vs)]
答案 0 :(得分:2)
你可以尝试
DT[cyl==6][,(mynames):= list(cumsum(mpg), cummin(disp),
rollmean(wt,k=2,fill=0,align="right")), by=.(am, vs)][]
# mpg cyl disp hp drat wt qsec vs am gear carb cumsum_mpg cummin_disp
#1: 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 21.4 258.0
#2: 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 39.5 225.0
#3: 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 58.7 167.6
#4: 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 76.5 167.6
#5: 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 21.0 160.0
#6: 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 42.0 160.0
#7: 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 61.7 145.0
# rollmean_wt
#1: 0.0000
#2: 3.3375
#3: 3.4500
#4: 3.4400
#5: 0.0000
#6: 2.7475
#7: 2.8225
或者,如果您需要按照与dplyr
DT <- as.data.table(mtcars)
setkey(DT, cyl)
DT[J(6)][, (mynames) := list(cumsum(mpg), cummin(disp),
rollmean(wt,k=2,fill=0,align="right")), by=.(am, vs)][]