r - 在列表中查找特定元素
问题描述
我被困在我正在阅读的教程中提出的挑战之一。
# Using the following code:
challenge_list <- list(words = c("alpha", "beta", "gamma"),
numbers = 1:10
letter = letters
# challenge_list
# Extract the following things:
#
# - The word "gamma"
# - The letters "a", "e", "i", "o", and "u"
# - The numbers less than or equal to 3
我尝试过使用以下内容:
## 1
challenge_list$"gamma"
## 2
challenge_list [[1]["gamma"]]
但没有任何效果。
解决方案
我们可以使用一个函数,然后执行子集(如果它是否为数字),然后使用将对应于原始元素Map
的 to 向量传递并应用. 这将返回带有ed 值的新值list
list
f1
list
filter
f1 <- function(x, y) if(is.numeric(x)) x[ x <= y] else x [x %in% y]
out <- Map(f1, challenge_list, list('gamma', 3, c("a","e","i","o","u")))
out
-输出
#$words
#[1] "gamma"
#$numbers
#[1] 1 2 3
#$letter
#[1] "a" "e" "i" "o" "u"
推荐阅读
- javascript - 使用正则表达式删除特殊字符
- java - 如何比较 4 个整数并返回它们的变量名?
- bazel - bazel 构建工具是否主要专注于单个 starlark 文件?
- google-sheets - 当我使用谷歌表格批量更新附加单元格请求时,如何摆脱类似日期的字符串前面的撇号?
- c# - Cefsharp:如何从设置中获取价值?
- django - 无法在弹性 beantalk django 应用程序上运行 supervisord celery 工作进程
- java - 当前的 CallableStatement 不是 ResultSet,但调用了 getResultList (MySQL)
- sql - SQL Server 中的游标只获取所有其他记录
- eclipse - 无法在 Ubuntu 上使用 jdk11 编译 JavaFX 应用程序
- javascript - 如何使用 XmlHttpRequest 在 Mvc 5 中从 Json 渲染 PartialView