我正在努力重新排序我的数据,以便在一个也使用 dplyr 的函数中使用 ggplot 进行绘图:
# example data
library(ggplot2)
library(dplyr)
dat <- data.frame(a = c(rep("l", 10), rep("m", 5), rep("o", 15)),
b = sample(100, 30),
c= c(rep("q", 10), rep("r", 5), rep("s", 15)))
这是我在函数之外的步骤:
# set a variable
colm <- "a"
# make a table
dat1 <- dat %>%
group_by_(colm) %>%
tally(sort = TRUE)
# put in order and plot
ggplot(dat2, aes(x = reorder(a, n), y = n)) +
geom_bar(stat = "identity")
但是当我试图把它变成一个函数时,我似乎不能使用
reorder
:f <- function(the_data, the_column){
dat %>% group_by_(the_column) %>%
tally(sort = TRUE) %>%
ggplot(aes_string(x = reorder(the_column, 'n'), y = 'n')) +
geom_bar(stat = "identity")
}
f(dat, "a")
Warning message:
In mean.default(X[[i]], ...) :
argument is not numeric or logical: returning NA
该功能将在没有
reorder
的情况下工作:f <- function(the_data, the_column){
dat %>% group_by_(the_column) %>%
tally(sort = TRUE) %>%
ggplot(aes_string(x = the_column, y = 'n')) +
geom_bar(stat = "identity")
}
f(dat, "a")
我可以在没有 dplyr 的情况下得到我想要的东西,但我更喜欢使用 dplyr,因为它在我的实际用例中效率更高:
# without dplyr
ff = function(the_data, the_column) {
data.frame(table(the_data[the_column])) %>%
ggplot(aes(x = reorder(Var1, Freq), y = Freq)) +
geom_bar(stat = "identity") +
ylab("n") +
xlab(the_column)
}
ff(dat, "a")
我看到其他人为此苦苦挣扎( 1 , 2 ),但似乎必须有一个更有效的 dplyr/pipe 习语来完成这个功能重排任务。
最佳答案
如果您打算使用 aes_string
,那么整个值必须是一个字符串,而不仅仅是部分字符串。您可以使用 paste()
帮助构建您要用于 x
的表达式.例如
f <- function(the_data, the_column){
dat %>% group_by_(the_column) %>%
tally(sort = TRUE) %>%
ggplot(aes_string(x = paste0("reorder(",the_column,", n)"), y = 'n')) +
geom_bar(stat = "identity")
}
或者你可以使用表达式而不是字符串
f <- function(the_data, the_column){
dat %>% group_by_(the_column) %>%
tally(sort = TRUE) %>%
ggplot(aes_q(x = substitute(reorder(x, n),list(x=as.name(the_column))), y = quote(n))) +
geom_bar(stat = "identity")
}
但总体思路是,在混合字符串和原始语言元素(如名称或表达式)时需要小心。
关于r - 函数 : use reorder in aes function 中的 dplyr 和 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35933199/