【问题标题】:Summary a list of integers into two columns in R将整数列表汇总为 R 中的两列
【发布时间】:2015-03-04 17:00:18
【问题描述】:

这是我得到的(列表):

>head(indexes)
[[1]]
numeric(0)

[[2]]
[1] 12

[[3]]
[1] 13

[[4]]
[1] 2 3

[[5]]
[1] 25

[[6]]
[1] 26

> all(vapply(indexes, is.numeric, TRUE)) # (note that..)
[1] TRUE

..这就是我想要的(对我来说信息相同):

>head(res,6)
     [,1] [,2]
[1,]    2   12
[2,]    3   13
[3,]    4    2
[4,]    4    3
[5,]    5   25
[6,]    6   36

有没有聪明的方法来做到这一点?

我尝试了一个命名列表的技巧:

names(indexes) <- 1:lenght(indexes)
res <- c(indexes, recursive=TRUE)
res <- cbind(as.integer(names(res)), res)

但是 R(真是个善良的孩子!)通过以模棱两可的方式重命名相同的行来打破一切:

>head(res)
      res
2   2   2
3   3   3
41 41   2
42 42   3
5   5   5
6   6   6

# ... (think about what happens around lines 3675.. 41158..)

.. 如果这是聪明的方法,我该如何防止重命名?

【问题讨论】:

  • cbind(rep(seq(idx), sapply(idx, length)), unlist(idx))(但不聪明)
  • @user20650 为什么不聪明? ^ ^

标签: r list matrix integer names


【解决方案1】:

哎呀!好的,搞定了:

res <- cbind(
  rep(1:length(indexes), vapply(indexes,length,1)),
   c(indexes,recursive=TRUE)
)

..如果有人找到更好的方法,请告诉我:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2021-02-05
    • 2021-04-23
    • 1970-01-01
    • 2020-07-15
    相关资源
    最近更新 更多