我正在尝试编写一个函数来对我的分组数据帧进行重复数据删除。它断言每个组中的值都是相同的,然后只保留组的第一行。我试图赋予它类似于pivot_longer()的tidyselect语义,因为我只需要将列名转发到summary(a = n_distinct(...))调用中。
所以对于一个示例表
test <- tribble(
~G, ~F, ~v1, ~v2,
"A", "a", 1, 2,
"A", "b", 1, 2,
"B", "a", 3, 3,
"B", "b", 3, 3) %>%
group_by(G)我期望调用remove_duplicates(test, c(v1, v2)) (使用tidyselect helper c()返回
G F v1 v2
A a 1 2
B a 1 2但我得到了
Error: `arg` must be a symbol我尝试使用新的"embrace"语法来解决这个问题(参见下面的函数代码),但失败了,并显示了上面显示的消息。
# Assert that values in each group are identical and keep the first row of each
# group
# tab: A grouped tibble
# vars: <tidy-select> Columns expected to be constant throughout the group
remove_duplicates <- function(tab, vars){
# Assert identical results for identical models and keep only the first per group.
tab %>%
summarise(a = n_distinct({{{vars}}}) == 1, .groups = "drop") %>%
{stopifnot(all(.$a))}
# Remove duplicates
tab <- tab %>%
slice(1) %>%
ungroup()
return(tab)
}我认为我需要以某种方式指定表达式vars的求值上下文必须更改为substitute当前正在求值的tab的子数据帧。所以就像这样
tab %>%
summarise(a = do.call(n_distinct, TIDYSELECT_TO_LIST_OF_VECTORS(vars, context = CURRENT_GROUP))))但我对技术细节的理解还不够深入,无法让它真正发挥作用……
发布于 2020-09-14 23:05:26
如果您先enquos您的vars,然后在结果上使用卷曲-卷曲运算符,这将按预期工作:
remove_duplicates <- function(tab, vars){
vars <- enquos(vars)
tab %>%
summarise(a = n_distinct({{vars}}) == 1, .groups = "drop") %>%
{stopifnot(all(.$a))}
tab %>% slice(1) %>% ungroup()
}所以现在
remove_duplicates(test, c(v1, v2))
#> # A tibble: 2 x 4
#> G F v1 v2
#> <chr> <chr> <dbl> <dbl>
#> 1 A a 1 2
#> 2 B a 3 3https://stackoverflow.com/questions/63885691
复制相似问题