我想编写一个函数,该函数具有数据集、要分组的变量和要过滤的另一个参数作为参数。我想以这样一种方式编写函数,以便之后我可以对其应用 map() 并将要分组的变量作为向量传递给 map()。不过,我不知道我的自定义函数 rating() 如何接受要分组为字符串的变量。这是我尝试过的。
data = tibble(a = seq.int(1:10),
g1 = c(rep("blue", 3), rep("green", 3), rep("red", 4)),
g2 = c(rep("pink", 2), rep("hotpink", 6), rep("firebrick", 2)),
na = NA,
stat=c(23,43,53,2,43,18,54,94,43,87))
rating = function(data, by, no){
data %>%
select(a, {{by}}, stat) %>%
group_by({{by}}) %>%
mutate(rank = rank(stat)) %>%
ungroup() %>%
filter(a == no)
}
fn(data = data, by = g2, no = 5) #this works
这就是我想使用我的功能的方式
map(.x = c("g1", "g2"), .f = ~rating(data = data, by = .x, no = 1))
...但我明白了
Error: Must group by variables found in `.data`.
* Column `.x` is not found.