在 R/Rcpp 中转置列表的最快方法 [英] Fastest way to transpose a list in R / Rcpp

查看:58
本文介绍了在 R/Rcpp 中转置列表的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单:

ls <- list(c("a", "b", "c"), c("1", "2", "3"), c("foo", "bar", "baz"))
ls

#> [[1]]
#> [1] "a" "b" "c"

#> [[2]]
#> [1] "1" "2" "3"

#> [[3]]
#> [1] "foo" "bar" "baz"

我希望转置"给:

resulting_ls

#> [[1]]
#> [1] "a"   "1"   "foo"

#> [[2]]
#> [1] "b"   "2"   "bar"

#> [[3]]
#> [1] "c"   "3"   "baz"

我可以通过以下方式实现:

I can achieve this with:

mat <- matrix(unlist(ls), ncol = 3, byrow = TRUE)
resulting_ls <- lapply(1:ncol(mat), function(i) mat[, i])

但是对于我的真实数据,它非常慢......(我需要为许多列表执行此操作,每个列表都比上面的示例大得多)

But with my real data it's very slow...(and I need to do this for many lists each of which are much larger than example above)

对于大列表length(ls) 和/或length(ls[[i]]),最快的方法是什么?

What is the fastest way to do this for a large list length(ls) and/or length(ls[[i]])?

  1. R 中(如果不是这样的话)
  2. 使用Rcpp
  1. in R (if this is not the case already)
  2. with Rcpp

推荐答案

data.table 包中,有一个 transpose() 函数就是这样做的.为了速度,它是用 C 实现的.

In the data.table package, there's a transpose() function which does exactly this. It is implemented in C for speed.

require(data.table) # v1.9.6+
transpose(ls)
# [[1]]
# [1] "a"   "1"   "foo"

# [[2]]
# [1] "b"   "2"   "bar"

# [[3]]
# [1] "c"   "3"   "baz"

如果列表元素的长度不相等,它还会自动填充 NA,并自动强制到最高的 SEXPTYPE.如有必要,您可以为 fill 参数提供不同的值.检查 ?transpose.

It also fills automatically with NA in case the list elements are not of equal lengths, and also coerces automatically to the highest SEXPTYPE. You can provide a different value to the fill argument if necessary. Check ?transpose.

这篇关于在 R/Rcpp 中转置列表的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆