数据表中的行最大值

时间:2015-02-12 19:56:21

标签: r data.table

我有一个8,000,000行的数据集,在data.table中有100列,其中每列都是一个计数。我需要找到每行中的最大计数以及该最大值所在的列。

我可以使用

快速获取哪一列具有每行的最大值
dt <- dt[, maxCol := which.max(.SD), by=pmxid]

但尝试使用

获取实际最大值
dt <- dt[, nmax := max(.SD), by=pmxid]

非常慢。我跑了近20分钟,计算出最多只有200,000行。找到最大列需要大约。所有8,000,000行的2分钟。

为什么找到最大值需要这么长时间?它不应该花费which.max()或更短的时间吗?

1 个答案:

答案 0 :(得分:8)

虽然,您正在寻找data.table解决方案,但这里有一个base R解决方案,对您的数据集来说足够快。

indx <- max.col(df, ties.method='first')
df[cbind(1:nrow(df), indx)]

在稍微大一点的数据集上,system.time比较显示

system.time({
 indx <- max.col(df1, ties.method='first')
 res <- df1[cbind(1:nrow(df1), indx)]
})
#   user  system elapsed 
# 2.180   0.163   2.345 



df1$pmxid <- 1:nrow(df1)
dt <- as.data.table(df1)
system.time(dt[, nmax:= max(.SD), by= pmxid])
#      user   system  elapsed 
#1265.792    2.305 1267.836 

base R方法要比帖子中的data.table方法更快。

数据

set.seed(24)
df <- as.data.frame(matrix(sample(c(NA,0:20), 20*10, 
       replace=TRUE), ncol=10))
#if there are NAs, change it to lowest number
df[is.na(df)] <- -999

set.seed(585)
df1 <- as.data.frame(matrix(sample(c(NA,0:20), 100*1e6,
 replace=TRUE), ncol=100))
df1[is.na(df1)] <- -999
相关问题