【发布时间】:2023-04-02 23:20:02
【问题描述】:
我有两个data.tables:
k1 <- mtcars[1:4,1:6]
k11 <- as.data.table(k1)
k2 <- iris[1:3,1:2]
k22 <- as.data.table(k2)
我正在尝试通过迭代第二个 data.table 的列行来对第一个 data.table 执行一些列操作
k3 <- lapply(1:nrow(k2),function(j){
mpg=k1[,"mpg"]*k2[j,"Sepal.Width"] #get the new value of mpg equals to mpg*first row of second column of second data.frame
cyl=k1[,"cyl"]*k2[j,"Sepal.Width"]
a3=k1[,3:6] #all remaining columns over which no operations are done
a4<-cbind(mpg,cyl,a3) #cbind these and create a new dataframe for each row of second dataframe. There are three rows and hence there will be three final dataset
})
#rbind all these dataset and get the new dataset
k4<-do.call(rbind,k3)
head(k4)
mpg cyl disp hp drat wt
Mazda RX4 73.50 30.6 160 110 3.90 2.620
Mazda RX4 Wag 73.50 30.6 160 110 3.90 2.875
Datsun 710 79.80 20.4 108 93 3.85 2.320
Hornet 4 Drive 74.90 30.6 258 110 3.08 3.215
虽然上面的解决方案很完美,但我想知道:
- 使用data.table是否有效率增益(因为这里没有
group_by操作)第一个数据帧为30000乘以10,#second数据帧为60乘以4(最终数据集将有30000次60:180 万行)。 - 如果有效率增益,使用
data.table如何获得效率:
以下是我的解决方案(类似于data.frame)
k5<-rbindlist(lapply(1:nrow(k2),function(j){
k11[,`:=`(mpg=mpg*k22[j,Sepal.Width],cyl=cyl*k22[j,Sepal.Length])]
}))
head(k5)
mpg cyl disp hp drat wt
1: 705.60 704.718 160 110 3.90 2.620
2: 705.60 704.718 160 110 3.90 2.875
3: 766.08 469.812 108 93 3.85 2.320
4: 719.04 704.718 258 110 3.08 3.215
5: 705.60 704.718 160 110 3.90 2.620
6: 705.60 704.718 160 110 3.90 2.875
你可以看到答案是不同的(我猜是因为 data.table 的复制性质)。
【问题讨论】:
标签: r data.table