r - 提取列表中向量的选定元素
问题描述
让我们考虑以下列表:
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 并不能解决问题(这是合乎逻辑的 - 它输出第一个元素的第一个元素,无论它是简单的字符串还是向量)。
你能帮我看看怎么做吗?
解决方案
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"
推荐阅读
- javascript - Javascript/Firestore: Uncaught (in promise) TypeError: firebase.firestore(...).collection(...).doc(...).collection(...).set is not a function
- python - pytest_bdd.exceptions.StepDefinitionNotFoundError 在 StepDefinition 中使用 parrs.re 时触发错误
- angular - 我应该订阅还是使用支持属性来更新组件中的依赖数据?
- python - 从 django 子进程调用 python,mysql not found 错误
- swift - 在选择器列表 SwiftUI 上添加搜索栏
- java - 在 .txt 文件中搜索字符串并获取 Java 中的行号和列号
- java - 实施 ViewModelProvider.Factory,我得到一个空指针异常
- html - Material UI Drawer 组件在未聚焦时添加不需要的阴影
- php - 比较多数组和一个数组
- html - 将新 div 悬停在旧 div 上会导致闪烁