masatotezuka
@masatotezuka (tezuka masato)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

【R】繰り返し処理で前処理〜可視化するにはどうすればいいでしょうか?

解決したいこと

繰り返し処理で前処理〜可視化をすること。
言語:R

サンプルデータ

df_example<-data.frame(
  shoujou=c("改善","改善なし","改善","改善","改善なし","改善","改善なし","改善","改善なし","改善","改善","改善なし","改善","改善なし","改善"),
  drugA= c("服用","服用なし","服用","服用なし","服用","服用なし","服用なし","服用","服用なし","服用","服用なし","服用","服用なし","服用","服用"),
  drugB= c("服用なし","服用","服用","服用","服用なし","服用なし","服用なし","服用なし","服用なし","服用","服用","服用","服用なし","服用","服用なし"),
  drugC= c("服用","服用なし","服用","服用なし","服用","服用","服用なし","服用","服用なし","服用","服用なし","服用","服用なし","服用なし","服用")
)

発生している問題・エラー

サンプルデータから、「syoujou」と「drugA」・「drugB」・「drugC」の相関をみるために繰り返し処理をして可視化したいと考えています。
しかし、下記のコードを実行しても、「syoujou」と「drugC」との相関を可視化したグラフしか出力されません。「syoujou」と「drugA」・「drugB」の相関を可視化したグラフも出力するにはどうすればいいでしょうか?
どなたか教えていただけると幸いです。
よろしくお願いいたします。

実行コード

library(tidyverse)
vars_drug<-names(df_example)[2:4]
drug_plots<-list()

for (i in length(vars_drug)) {
  df_example2 <-data.frame()
  df_example2 <-df_example %>% 
    group_by(shoujou, df_example[i+1] ) %>% 
    summarise(count=n()) 
  drug_plots[[i]]<-df_example2 %>%
    arrange(shoujou, desc(df_example2[2]))%>%
    mutate(label_y = (cumsum(count) - 0.5 * count) / sum(count)) %>%
    ggplot2::ggplot(aes_string(x = "shoujou",y="count"))+
    geom_bar(mapping = aes_string(x = "shoujou",y= "count" ,fill = colnames(df_example2[2])), stat = "identity",position = "fill") +
    theme_bw(base_family = "HiraKakuProN-W3") +
    labs(x = "症状改善の有無", y = "割合")+
    geom_text(aes(label = count, y = label_y))+
    scale_y_continuous(labels = scales::percent)
  print(drug_plots[[i]])
}

コードの実行結果

drugCのグラフのみ出力。

スクリーンショット 2022-02-26 12.56.34.png

0

No Answers yet.

Your answer might help someone💌