首页 > 解决方案 > 在列表中查找特定元素

问题描述

我被困在我正在阅读的教程中提出的挑战之一。

# 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"]]

但没有任何效果。

标签: r

解决方案


我们可以使用一个函数,然后执行子集(如果它是否为数字),然后使用将对应于原始元素Map的 to 向量传递并应用. 这将返回带有ed 值的新值listlistf1listfilter

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"

推荐阅读