我正在努力重新排序我的数据,以便在也使用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")
如果要使用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")
}
但是一般的想法是,在混合字符串和原始语言元素(例如名称或表达式)时,需要小心。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句