簡體   English   中英

dplyr:如何使用 count() 將列保留在 tibble 中

[英]dplyr: how to keep a column in a tibble using count()

我有

>head(p)
   study treatment response
1     14       SSA        3
2      1      SSTR        4
3     14       SSA        3
4      6      SSTR        3
5     10       SSA        4

我想計算每個studyresponse ,然后添加bind_rows以獲得所有response

因此,我有

  p %>% as_tibble() %>% 
  mutate(nystudie=as.character(study),
         best.resp =as.factor(response)) %>% 
  bind_rows(., mutate(., nystudie="All")) %>% 
  count(nystudie, best.resp)

屈服

# A tibble: 27 x 3
   nystudie best.resp     n
   <chr>    <fct>     <int>
 1 1        3             2
 2 1        4             3
 3 10       4             2
 4 11       3             1

然而,我想要做一個facet_wrap使用這ggplot tibble分層為p$treatment ,ALA + facet_wrap(., treatment) + ...

因此,我正在尋求有關如何優化我的腳本的幫助,以便預期的輸出類似於:

# A tibble: 27 x 3
   nystudie best.resp     n      treatment
   <chr>    <fct>     <int>          <fct>
 1 1        3             2         "SSTR"
 2 1        4             3         "SSTR"
 3 10       4             2         "SSTR"
 4 11       3             1          "SSA"

數據

p <- structure(list(study = structure(c(13L, 2L, 1L, 4L, 4L, 8L, 1L, 
3L, 1L, 4L, 12L, 1L, 13L, 1L, 8L, 1L, 6L, 4L, 9L, 13L, 14L, 1L, 
8L, 12L, 5L, 11L, 13L, 8L, 4L, 8L, 9L, 4L, 11L, 1L, 4L, 9L, 4L, 
15L, 11L, 9L, 12L, 2L, 11L, 6L, 12L, 12L, 8L, 10L, 4L, 2L), .Label = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "22"), class = "factor"), treatment = structure(c(2L, 
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 
1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 
1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 
1L), .Label = c("SSTR", "SSA"), class = "factor"), response = c("1", 
"3", "4", "3", "3", "3", "3", "3", "3", "3", "4", "4", "4", "3", 
"2", "4", "4", "4", "4", "4", "4", "4", "1", "3", "3", "4", "4", 
"1", "4", "1", "4", "4", "4", "3", "3", "2", "3", "4", "4", "2", 
"3", "3", "3", "4", "3", "4", "2", "4", "4", "3")), row.names = c(NA, 
-50L), class = "data.frame")

嘗試這個:

#Code
p %>%
  mutate(nystudie=as.character(study),
         best.resp =as.factor(response)) %>% 
  bind_rows(., mutate(., nystudie="All")) %>%
  group_by(nystudie,best.resp) %>%
  summarise(N=n(),Val=unique(treatment))

輸出:

# A tibble: 28 x 4
# Groups:   nystudie, best.resp [26]
   nystudie best.resp     N Val  
   <chr>    <fct>     <int> <fct>
 1 1        3             4 SSTR 
 2 1        4             4 SSTR 
 3 10       4             1 SSA  
 4 11       3             1 SSA  
 5 11       4             3 SSA  
 6 12       3             3 SSA  
 7 12       4             2 SSA  
 8 13       1             1 SSA  
 9 13       4             3 SSA  
10 14       4             1 SSA  
# ... with 18 more rows

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM