问题
This is likely a syntax question. Here's the problem recreated with some dummy data.
I'm working with a larger dataset, and I want to perform a group_nest and then create some plots with the title of the group. All goes well, until the title is just repeated.
library(tidyverse)
N <- 30
df <- tibble(type = rep(c("small","medium","high"), each=N/3),
dummy = rep(c(1,5,10),each=10),
xvals = rep(1:10,3),
A = rnorm(N)*dummy,
B = rnorm(N)*dummy,
C = rnorm(N)*dummy) %>%
mutate(type = factor(type, levels=c("small","medium","high"))) %>%
pivot_longer(cols=-c(type,xvals), names_to="metric", values_to = "value") %>%
group_by(type) %>%
group_nest(.key="data") %>%
mutate(gplot = map(data, ~ggplot(data=.x, aes(x=xvals,y=value))+
geom_point() +
facet_grid(rows=vars(metric)) +
ggtitle(paste0(type) ## THIS IS WHERE THE PROBLEM IS ##
)))
#view the plots
df$gplot[[1]] #has title "small"
df$gplot[[2]] #has title "small", should be "medium"
df$gplot[[3]] #has title "small", should be "large"
Here's what I get:
This is what I want:
回答1:
Maybe try map2
instead?
df <- tibble(type = rep(c("small","medium","high"), each=N/3),
dummy = rep(c(1,5,10),each=10),
xvals = rep(1:10,3),
A = rnorm(N)*dummy,
B = rnorm(N)*dummy,
C = rnorm(N)*dummy) %>%
mutate(type = factor(type, levels=c("small","medium","high"))) %>%
pivot_longer(cols=-c(type,xvals), names_to="metric", values_to = "value") %>%
group_by(type) %>%
group_nest(.key="data") %>%
mutate(gplot = map2(data,type, ~ggplot(data=.x, aes(x=xvals,y=value))+
geom_point() +
facet_grid(rows=vars(metric)) +
ggtitle(.y ## THIS IS WHERE THE PROBLEM IS ##
)))
来源:https://stackoverflow.com/questions/58383438/adding-grouped-variable-name-to-plot-with-group-nest-and-map