【发布时间】:2016-06-26 06:48:43
【问题描述】:
我正在努力重新排序我的数据,以便在一个也使用 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 习惯用法来完成这个函数中的重新排序任务。
【问题讨论】: