【问题标题】:Problems creating list of lists in R在 R 中创建列表的问题
【发布时间】:2013-07-08 13:08:00
【问题描述】:

我一直在尝试在 R 中创建一个列表列表。我首先创建一个预先指定长度的列表列表。然后,我使用 for 循环遍历矩阵以填充列表。

问题是我似乎正在获取列表列表等列表。

我的代码:

potential_dups <- rep(list(list()), 10)
nearest10 <- matrix(rnorm(100), nrow=10)

for (i in 1:length(nearest10[ , 1])) {
  for (j in 1:10) {
    if (nearest10[i, j] < 0.35 && nearest10[i, j] > 0) {
      potential_dups[[i]] <- append(potential_dups[[i]], nearest10[i, j])
    }
  } 
}  

为什么会这样?如何创建这种格式的列表?

[[1]]
[1] "Element 1A"
[[1]]
[2] "Element 1B"
[[1]]
[3] "Element 1C"

[[2]]
[1] "Element 2A"
[[2]]
[2] "Element 2B"

此外,我最终得到了一个空列表,例如: [[3]] 列表() 第一个元素是NULL。我还想编写脚本,仅从该数据结构中提取非空列表。

【问题讨论】:

  • 你为什么用append
  • @Roland 我在之前的 stackoverflow 示例中看到了它。我试过把它拿出来用c,但还是不行。
  • 请通过添加dput(nearest10_scores) 的输出使您的代码可重现。
  • @Roland 好的,我从 user2568961 借用了代码以使我的可重现。

标签: r list append subset nested-lists


【解决方案1】:

尽管您的示例不可重现,但我得到了一个包含以下类似代码的列表列表:

potential_dups <- rep(list(list()), 10)
nearest10 <- matrix(rnorm(100), nrow=10)
for (i in 1:10) {
  for (j in 1:10) {
    if (nearest10[i, j] < 0.35 & nearest10[i, j] > 0) {
      potential_dups[[i]] <- append(potential_dups[[i]], nearest10[i, j])
    }
  } 
}  

要删除空列表,您可以这样做:

potential_dups[sapply(potential_dups, function(x) length(x) > 0)]

【讨论】:

  • 这与我的代码相同。这不会产生列表列表的列表吗?
  • 不,它会产生一个列表列表。
  • @user2568961 这回答了我关于您使用 sapply 函数的第二个问题。谢谢。
【解决方案2】:

这是一个更好的(更好的可读性和更有效的)方式:

mat <- nearest10
mat[mat >= 0.35 | mat <= 0] <- NA
potential_dups <- apply(mat,1,function(x) as.list(na.omit(x)))

但是,我无法想象你为什么想要这个输出。它似乎不是最有用的。也许您可以改用以下内容?

potential_dups <- apply(mat,1,function(x) c(na.omit(x)))

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多