私はこれを克服しようとしています。これ以上取得できません。
因子変数と数値変数を持つデータフレームがあります。これにより、最初の数行と列が表示されます。
# 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"]
次の2つのコードスニペットは、必要なプロットを生成します。
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")
私の目標は、データフレーム内の変数と同じ数のグラフを作成し、列をループして、そのようなグラフを1つのシートに格納することです。
私の試みは
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(data、unname(vars)、drop)のエラー:列i
が不明です
その上、そのコードではすべてのグラフが1枚のシートに表示されるわけではありません。どんな助けでも大歓迎です!!!
上記のリンクは良いリファレンスです。または、Rstudioのtidyevalチートシートを参照してください:https://github.com/rstudio/cheatsheets/raw/master/tidyeval.pdf
i
ggplotステートメントで評価するには、!!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)
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加