Fastest way to transpose a list in R / Rcpp

后端 未结 2 1568
轻奢々
轻奢々 2021-01-17 18:19

I have a list:

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

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

#>         


        
2条回答
  •  走了就别回头了
    2021-01-17 19:13

    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"
    

    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.

提交回复
热议问题