I cannot find an answer to this simple problem:
I want to create a ggplot. The aes parameter come partially from vector and partially are assigned directly.
names(mydt)
"gender" "cat1" "category_b" "value"
category_a <- "cat1"
plot.sum <- mydt %>%
dplyr::group_by(category_a, category_b) %>%
ggplot(aes(x = category_a, y = N, fill = category_b)) +
geom_bar(position="stack", stat="identity")
plot.sum
This does not work and i get an error:
Error: Column category_a is unknown
I assume this is because R expects category_a to be a column in mydt and instead it gets an character item from a vector "cat1", which does not exist in mydt - correct me if i am wrong?
How can this be fixed?
The ultimate goal is to make this to a function:
make.plot.sum <- function (data, group_by1, group_by2, position){
data %>%
dplyr::group_by(group_by1, group_by2) %>%
ggplot(aes(x = group_by1, y = N, fill = group_by2)) +
geom_bar(position="position", stat="identity")
plot.sum
return(plot.sum)
}
make.plot.sum(mydt, category_a, category_b, stack)
aes(x = {{group_by1}}, y = N, fill = {{group_by2}})?aes(x = .data[[group_by1]], y = N, fill = .data[[group_by2]])? I think the post on this piece of nonstandard evaluation can be found here: tidyverse.org/blog/2019/06/rlang-0-4-0