我写了一段代码,我想在不同的变量上运行
#ggplot frequency table
marso <- some_dataset %>%
count(some_variable)
##ggplot arrange
taart_marso <- marso %>%
arrange(desc(some_variable)) %>%
mutate(prop = round(n*100/sum(n), 1),
lab.ypos = cumsum(prop) - 0.5*prop)
head(taart_marso, 4)
##ggplot piechart
ggplot(taart_marso, aes(x = "", y = prop, fill = some_variable)) +
geom_bar(width = 1, stat = "identity", color = "white") +
geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
coord_polar("y", start = 0)+
theme_void()
我将上面的内容粘贴到一个函数中,并尝试使用相同的变量和数据集调用该函数
piechart <- function(dataset, variable) {
mar <- dataset %>%
count(variable)
taart_mar <- mar %>%
arrange(desc(variable)) %>%
mutate(prop = round(n*100/sum(n), 1),
lab.ypos = cumsum(prop) - 0.5*prop)
ggplot(taart_mar, aes(x = "", y = prop, fill = variable)) +
geom_bar(width = 1, stat = "identity", color = "white") +
geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
coord_polar("y", start = 0)+
theme_void()
}
piechart("some_dataset", "some_variable")
如果我这样做,我会收到以下错误:
Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "character"
有人能帮忙吗?
最佳答案
使用 tidyverse
,如果我们传递一个不带引号的参数,我们可以使用 {{}}
piechart <- function(dataset, variable) {
mar <- dataset %>%
count({{variable}})
taart_mar <- mar %>%
arrange(desc({{variable}})) %>%
mutate(prop = round(n*100/sum(n), 1),
lab.ypos = cumsum(prop) - 0.5*prop)
ggplot(taart_mar, aes(x = "", y = prop, fill = {{variable}})) +
geom_bar(width = 1, stat = "identity", color = "white") +
geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
coord_polar("y", start = 0)+
theme_void()
}
piechart(mtcars, vs)
注意:不应引用数据集对象,因为它会导致使用 get
来提取值,并且会产生不必要的错误。另外,aes
中的x = ""
也不清楚。因此,请务必在必要时更改该部分
如果我们需要将带引号的字符串作为变量名传递,请使用 ensym
将其转换为 sym
bol 并计算 (!!
)
piechart <- function(dataset, variable) {
variable <- rlang::ensym(variable)
mar <- dataset %>%
count(!!variable)
taart_mar <- mar %>%
arrange(desc(!!variable)) %>%
mutate(prop = round(n*100/sum(n), 1),
lab.ypos = cumsum(prop) - 0.5*prop)
ggplot(taart_mar, aes(x = "", y = prop, fill = !!variable)) +
geom_bar(width = 1, stat = "identity", color = "white") +
geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
coord_polar("y", start = 0)+
theme_void()
}
piechart(mtcars, "vs")
关于r - 函数内的计数(dplyr)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59178124/