[英]Extract chosen element of the vector in the list
Let's consider list following:让我们考虑以下列表:
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))
)
As you can see first element of the list is a string or vector of strings.如您所见,列表的第一个元素是字符串或字符串向量。 What I want to have is to extract specific element, regardless it's in a vector or not.我想要的是提取特定元素,无论它是否在向量中。
In this example I would like to have for extracting first element:在这个例子中,我想提取第一个元素:
"something", "cool", "big", "huge"
If second then如果是第二个
"small", "not"
If third then如果是第三个
"small"
because I'm always extracting the very first element.因为我总是提取第一个元素。
And I'm not sure how to do it in the simpler way.而且我不确定如何以更简单的方式做到这一点。 I tried with sapply:我试过 sapply:
unlist(sapply(listed_list, "[[", 1))
but pure use of sapply is not solving the issue (which is logical - it output first element of the first regardless it's simple string or vector).但纯粹使用 sapply 并不能解决问题(这是合乎逻辑的 - 它是 output 第一个元素的第一个元素,无论它是简单的字符串还是向量)。
Could you please give me a hand how it can be done?你能帮我看看怎么做吗?
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.