【发布时间】:2020-04-16 20:23:35
【问题描述】:
我正在尝试创建一个函数,我可以在其中将列名作为参数传递。我已经看到过类似post on passing column names to a function 的其他一些示例,但我收到了一个错误:
错误:
column列未知
这是我 csv 中的数据:
Role
1 Primary
2 Secondary
3 Primary
4 Primary
这是我的代码:
mydata = read.csv("EA5.csv")
my_bar_chart <- function(data, column, title){
column<-eval(substitute(column),data, parent.frame())
toReturn <- data %>%
group_by(column) %>%
summarize(count = n()) %>%
mutate(percent = count/sum(count), column = reorder(column, -count, FUN=identity)) %>%
ggplot(aes(x=column, y=count)) +
xlab(title)+
geom_col() +
geom_text(aes(label = paste0(round(100 * percent, 1), "%")))
return(toReturn)
}
p1 <- my_bar_chart(mydata, Role, "EA5 Controller Role")
grid.arrange(p1)
【问题讨论】:
-
您正在寻找非标准评估 (NSE)。也许dplyr.tidyverse.org/articles/programming.html 可以提供帮助。
-
欢迎来到 Stack Overflow!您能否通过分享您的数据样本来重现您的问题,以便其他人可以提供帮助(请不要使用
str()、head()或屏幕截图)?你可以使用reprex和datapasta包来帮助你。另见Help me Help you & How to make a great R reproducible example? -
我模糊的记忆是你可能想要 dplyr
!!和!!!函数。此外,使用未定义的Role对象调用您的函数应该会引发错误,因此您没有告诉我们足够多的信息来提供建议。 -
我已更新问题以包含数据。 (列标题称为“角色”)
标签: r function ggplot2 dplyr tidyverse