gpt4 book ai didi

r - 如何根据外部列向量过滤 R 数据表

转载 作者:行者123 更新时间:2023-12-01 02:06:04 25 4
gpt4 key购买 nike

我有兴趣过滤 R 数据表以选择相应的行元素
到数字列的列表。

例如,假设我有:

DT<- data.table(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9))

这使,
   a b c
1: 1 4 7
2: 2 5 8
3: 3 6 9

现在,我有一个名为 select 的外部向量,其中包含我想要选择的与行相对应的列。
select <- c(2,3,1)

我希望它返回一个新的数据表,该数据表的每一行值都对应于所选列。
DTnew 
1: 4
2: 8
3: 3

如果我尝试类似 DT[,.SD[select]] ,它返回一个新的数据表,其中包含与选择列表对应的整行。
> DT[,.SD[select]]
a b c
1: 2 5 8
2: 3 6 9
3: 1 4 7

我怎样才能完成这个任务?

编辑:我没有说清楚,但结果需要保留数据表行的原始顺序,因为它是基于时间序列的对象(我省略了 ts 索引以使问题更简单)。

更新 2:一些已发布解决方案的计时结果(使用数据表方法在系统时间上似乎要快得多,不确定如何得出用户和耗时/开销的结果,但我也想在整个过程中与数据表保持一致。猜猜我还应该问一下,当速度优先时,DT 用户是否经常来回进行基于矩阵的计算)。
library(data.table)
library(microbenchmark)

set.seed(123)

DT <- data.table(matrix(rnorm(10e3*10e3),nrow=10e3,ncol=10e3))
select<-sample(10e3,replace=FALSE)

op <- microbenchmark(
sol1 <- function(DT,select) DT[, V1 := .SD[[select]], by = select]$V1,

sol2 <- function(DT,select) {
x <- as.matrix(DT)
x[cbind(1:nrow(x), select)]
},

times=1000L)

Warning message:
In microbenchmark(sol1 <- function(DT, select) DT[, `:=`(V1, .SD[[select]]), :
Could not measure a positive execution time for 1019 evaluations.


> identical(sol1(DT,select),sol2(DT,select))
[1] TRUE
> op
Unit: nanoseconds
expr min lq mean median uq max neval cld
sol1 <- function(DT, select) DT[, `:=`(V1, .SD[[select]]), by = select]$V1 0 0 25.136 0 1 9837 1000 a
sol2 <- function(DT, select) { x <- as.matrix(DT) x[cbind(1:nrow(x), select)] } 0 0 52.477 0 1 39345 1000 a

方法二:
> system.time(replicate(10,sol1(DT,select)))
user system elapsed
64.07 0.25 64.33
> system.time(replicate(10,sol2(DT,select)))
user system elapsed
4.97 2.25 7.22

最佳答案

您可以使用矩阵索引对矩阵执行此操作:

x <- as.matrix(DT)
x[cbind(1:nrow(x), select)]
## [1] 4 8 3

如果您从数据框开始,您还可以使用矩阵对其进行索引:
x <- data.frame(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9)) # or as.data.frame(DT)
x[cbind(1:nrow(x), select)]
## [1] 4 8 3

关于r - 如何根据外部列向量过滤 R 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32622171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com