我正在努力克服这一点。不能再走了。

我有一个包含因子和数字变量的数据框。随即显示前几行和几列。

# A tibble: 6 x 5
  cluster SEV_D SEV_M   OBS   PAN
    <int> <dbl> <dbl> <fct> <fct>
1       1     5     1    0     1
2       2     6     1    0     0
3       1     5     1    0     1
4       2     4     2    0     0
5       1     4     1    1     1
6       1     4     2    1     0

cluster=as.factor(c(1,2,1,2,1,1))
SEV_D=as.numeric(c(5,6,5,4,4,4))
SEV_M=as.numeric(c(1,1,1,2,1,2))
OBS=as.factor(c(0,0,0,0,1,1))
PAN=as.factor(c(1,0,1,0,1,0))
data<-data.frame(cluster,SEV_D,SEV_M,OBS,PAN)

我将这样的数据框分成数值和因子变量,在两个子集中都保留了“簇”,因为我需要它进行分组。
data_fact <- data[, sapply(data, class) == 'factor']

data_cont <- data[, sapply(data, class) == 'numeric' | names(data)
== "cluster"]

以下两个代码片段将生成我想要的图。
data_fact %>% group_by(cluster,OBS)%>%summarise(total.count=n()) %>%
ggplot(., aes(x=cluster, y=total.count, fill=OBS)) +
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=total.count),
position=position_dodge(width=0.9), vjust=-0.2)

data_cont %>% group_by(cluster) %>% dplyr::summarise(mean =
mean(SEV_D), sd = sd(SEV_D)) %>%
ggplot(.,aes(x=cluster,y=mean))+geom_bar(position=position_dodge(),
stat="identity",colour="black",size=.3)+geom_errorbar(aes(ymin=mean-
sd, ymax=mean+sd),size=.3,width=.4,position=position_dodge(.4)) +
ggtitle("SEV_D")

我的目标是在数据框中创建与变量一样多的图,遍历各列,并将这些图存储在一张纸中。

我的尝试是
col<-names(data_fact)[!names(data_fact)%in%"cluster"]

for(i in col) {
data_fact %>% group_by(cluster,i)%>%summarise(total.count=n()) %>%
ggplot(., aes(x=cluster, y=total.count, fill=i)) + geom_bar(position
= 'dodge', stat='identity') + geom_text(aes(label=total.count),
position=position_dodge(width=0.9), vjust=-0.2)
}

但这会引发此错误:

在grouped_df_impl中出错(数据,未命名(变量),删除):
i不明

最重要的是,该代码恐怕不会在一张纸上显示所有图形。任何帮助将非常感激!!!

最佳答案

上面的链接是一个很好的参考。或查看Rstudio的tidyeval速查表:https://github.com/rstudio/cheatsheets/raw/master/tidyeval.pdf

要在ggplot语句中评估i,您需要使用!!ensym( )函数构造取消对字符串的引用。同样,您将需要使用print语句在循环中打印图表。

library(ggplot2)

col<-names(data_fact)[!names(data_fact)%in%"cluster"]

for(i in col) {
   print(i)

   g<-data_fact %>% group_by(cluster, !!ensym(i)) %>% summarise(total.count=n()) %>%
     ggplot(., aes(x=cluster, y=total.count, fill=!!ensym(i))) +
     geom_bar(position  = 'dodge', stat='identity') +
     geom_text(aes(label=total.count), position = position_dodge(width=0.9), vjust=-0.2) +
     labs(title=i)
  print(g)
}

10-04 21:54
查看更多