提取数据帧列表 R 中单列的重复观察值

问题描述 投票:0回答:1

我有以下可重现的示例:

# I have 4 dataframes in a listy with a few observations that repeat themselves
df_1 <- data.frame(x = c(1, 2, 3, 4), y = c('apple', 'pineapple', 'orange', 'grape'))
df_2 <- data.frame(x = c(2, 3, 4, 5, 6, 7), y = c('watermelon', 'orange', 'halibut', 'apple', 'iron', 'grape'))
df_3 <- data.frame(x = c(2, 3, 4, 5, 6, 7, 9, 0), y = c('rock', 'pineapple', 'apple', 'tire', 'bomb', 'star', 'coconut', 'grape'))
df_4 <- data.frame(x = c(1, 4, 9), y = c('grape', 'apple', 'rock'))

# All inside a another list
df_list <- list(df_1, df_2, df_3, df_4)

我想要一个函数,它返回每个数据帧中

y
列中重复的值,而忽略列中观察的顺序,因此函数的结果应该只是:

[1] "apple" "grape"

我已经尝试过

reduce(intersect, big_list)
,但该函数没有捕获数据帧中的所有重复值。这可能是因为每列中重复值的位置不相同,或者因为列表中的数据帧之间的列大小不相等。

r dataframe nested-lists
1个回答
0
投票

要查找出现在所有数据框中的值,您可以使用

Reduce()
:

Reduce(intersect, lapply(df_list, \(df) df$y))
# [1] "apple" "grape"
© www.soinside.com 2019 - 2024. All rights reserved.