我有1个数据框的数据和多个“参考”数据框。我正在尝试自动检查数据框的值是否与参考数据框的值匹配。重要的是,这些值还必须与参考数据帧中的值具有相同的顺序。这些列很重要,但是我的实际数据集包含更多列。
下面是一个玩具数据集。
Dataframe
group type value
1 A Teddy
1 A William
1 A Lars
2 B Dolores
2 B Elsie
2 C Maeve
2 C Charlotte
2 C Bernard
Reference_A
type value
A Teddy
A William
A Lars
Reference_B
type value
B Elsie
B Dolores
Reference_C
type value
C Maeve
C Hale
C Bernard
例如,在玩具数据集中,group1的得分为1.0(100%正确),因为它在A中的所有值都与reference_A中An的值和值顺序匹配。但是,第2组的得分是0.0,因为B中的值与reference_B相比是乱序,而0.66是因为C中的2/3值与reference_C中的值和值顺序匹配。
所需的输出
group type score
1 A 1.0
2 B 0.0
2 C 0.66
这很有帮助,但没有考虑顺序: Check whether values in one data frame column exist in a second data frame
更新:谢谢所有提供解决方案的人!这些解决方案非常适合玩具数据集,但尚未适用于具有更多列的数据集。再次,就像我在帖子中所写的那样,上面列出的列很重要-我宁愿不要在必要时删除不需要的列。
答案 0 :(得分:2)
这是另一个tidyverse
解决方案。在这里,我要为引用和数据添加一个计数器(即 rowname
)。然后,我将他们一起加入type
和rowname
上。最后,我在type
上对其进行了总结,以获得所需的输出。
library(dplyr)
library(purrr)
library(tibble)
list(`Reference A`, `Reference B`, `Reference C`) %>%
map(., rownames_to_column) %>%
bind_rows %>%
left_join({Dataframe %>%
group_split(type) %>%
map(., rownames_to_column) %>%
bind_rows},
. , by=c("type", "rowname")) %>%
group_by(type) %>%
dplyr::summarise(group = head(group,1),
score = sum(value.x == value.y)/n())
#> # A tibble: 3 x 3
#> type group score
#> <chr> <int> <dbl>
#> 1 A 1 1
#> 2 B 2 0
#> 3 C 2 0.667
答案 1 :(得分:2)
我们还可以使用es2015
来执行此操作,以返回mget
的{{1}},将它们绑定在一起,并按逻辑向量list
进行分组
data.frames
答案 2 :(得分:1)
这是一种“整洁”的方法:
ScreenManager