首页 > 解决方案 > 提取列表中向量的选定元素

问题描述

让我们考虑以下列表:

listed_list <- list(
  list("something", 2), list("cool", 3),
  list(c("big", "small"), c(2, 3)),
  list(c("huge", "not", "small"), c(3, 4, 5))
)

如您所见,列表的第一个元素是字符串或字符串向量。我想要的是提取特定元素,无论它是否在向量中。

在这个例子中,我想提取第一个元素:

"something", "cool", "big", "huge"

如果是第二个

"small", "not"

如果是第三个

"small"

因为我总是提取第一个元素。

而且我不确定如何以更简单的方式做到这一点。我试过 sapply:

unlist(sapply(listed_list, "[[", 1))

但纯粹使用 sapply 并不能解决问题(这是合乎逻辑的 - 它输出第一个元素的第一个元素,无论它是简单的字符串还是向量)。

你能帮我看看怎么做吗?

标签: rstringlistcharacter

解决方案


foo <- function(L, i) {
  res <- lapply(L, "[[", 1)
  res <- res[lengths(res) >= i]
  vapply(res, "[[", i, FUN.VALUE = character(1))
}

foo(listed_list, 1)
#[1] "something" "cool"      "big"       "huge"   
foo(listed_list, 2)
#[1] "small" "not" 
foo(listed_list, 3)
#[1] "small"

推荐阅读