ID <- c(1,2,3,4,5)
DrugA <- c(1,1,0,0,0)
DrugB <- c(0,0,1,0,1)
TreatmentLevel <- c("Inpatient","Outpatient","Outpatient","Inpatient","Outpatient")
df <- data.frame(ID,DrugA,DrugB,TreatmentLevel)
df %>%
pivot_longer(starts_with("Drug"), names_to = "Var") %>%
group_by(TreatmentLevel, Var) %>%
summarise(value = sum(!is.na(value))) %>%
pivot_wider(names_from = TreatmentLevel, values_from = value)
# A tibble: 2 x 3
Var Inpatient Outpatient
<chr> <int> <int>
1 DrugA 2 3
2 DrugB 2 3我想把这些数据汇总到下表中。但我的桌子弄错了。你还能帮我用ggplot2画一张图吗?


发布于 2022-07-11 21:30:58
问题是您还计算了0值。要获得您想要的结果,您可以这样做:
library(dplyr)
library(tidyr)
library(ggplot2)
tbl <- df %>%
pivot_longer(starts_with("Drug"), names_to = "Var") %>%
count(TreatmentLevel, Var, wt = value)
tbl
#> # A tibble: 4 × 3
#> TreatmentLevel Var n
#> <chr> <chr> <dbl>
#> 1 Inpatient DrugA 1
#> 2 Inpatient DrugB 0
#> 3 Outpatient DrugA 1
#> 4 Outpatient DrugB 2
ggplot(tbl, aes(Var, n, fill = TreatmentLevel)) +
geom_col(position = "dodge2")

https://stackoverflow.com/questions/72944656
复制相似问题