对 data.table 进行高效的逐行操作 [英] Efficient row-wise operations on a data.table
本文介绍了对 data.table 进行高效的逐行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到许多 (+60) 相对较大 data.frame
(~ 250,000 x 3) 的行最小值(或者我可以等效地处理 xts代码>).
I need to find the row-wise minimum of many (+60) relatively large data.frame
(~ 250,000 x 3) (or I can equivalently work on an xts
).
set.seed(1000)
my.df <- sample(1:5, 250000*3, replace=TRUE)
dim(my.df) <- c(250000,3)
my.df <- as.data.frame(my.df)
names(my.df) <- c("A", "B", "C")
数据框my.df
如下所示
> head(my.df)
A B C
1 2 5 2
2 4 5 5
3 1 5 3
4 4 4 3
5 3 5 5
6 1 5 3
我试过了
require(data.table)
my.dt <- as.data.table(my.df)
my.dt[, row.min:=0] # without this: "Attempt to add new column(s) and set subset of rows at the same time"
system.time(
for (i in 1:dim(my.dt)[1]) my.dt[i, row.min:= min(A, B, C)]
)
在我的系统上,这大约需要 400 秒.它有效,但我不相信这是使用 data.table
的最佳方式.我是否正确使用 data.table
?有没有更高效的如何进行简单的逐行操作?
On my system this takes ~400 seconds. It works, but I am not confident it is the best way to use data.table
.
Am I using data.table
correctly? Is there a more efficient
way to do simple row-wise opertations?
推荐答案
或者,只是 pmin
.
my.dt <- as.data.table(my.df)
system.time(my.dt[,row.min:=pmin(A,B,C)])
# user system elapsed
# 0.02 0.00 0.01
head(my.dt)
# A B C row.min
# [1,] 2 5 2 2
# [2,] 4 5 5 4
# [3,] 1 5 3 1
# [4,] 4 4 3 3
# [5,] 3 5 5 3
# [6,] 1 5 3 1
这篇关于对 data.table 进行高效的逐行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文