簡體   English   中英

R代碼將group_by多列,並在列組中出現數據元素時匯總

[英]R code that will group_by multiple columns and summarize when a data element appears across the column group

如何總結出現在一組列中的一組特定因子的計數?

我正在總結一組特定因子,這些因素出現在我的數據集中的一組列中(具體而言,可以出現在15個不同的過程列中的醫療過程代碼)。 我想對列進行分組,然后在任何一列代碼中出現一組代碼列表時進行匯總。 這可能意味着指定的代碼與單個數據記錄不相互排斥,我正在尋找的多個過程代碼將在一行外觀中重疊。

我使用以下虛擬df來運行快速測試。 我想總結“Y”和“Z”列之間數據點“b”和“e”的計數。 顯然,我的總結不會像我想要的那樣有效,但就我而言。

library(dplyr)

Mydata <- data.frame(W = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                     X = c(20, 30, 45, 54, 65, 78, 97, 102, 123, 156),
                     Y = c("a","b","c","d","e","e","f","f","f","g"),
                     Z = c("c","a","b","b","c","d","e","e","g","h"))

 test_group <- Mydata %>%   summarize_at(c(z, w), n = n())

預期結果將是以下表格:

Specified_Data  n
             b  3
             e  4

另一個用戶發布了一個答案,但看起來他們把它拉了下來。 但是,它確實有效,所以我想我會拋出代碼。與dplyr一起工作。

Mydata %>%
  select(Y, Z) %>%
  gather(var, val) %>%
  filter(val %in% c("b", "e")) %>%
  count(val)

# A tibble: 2 x 2
  val       n
  <chr> <int>
1 b         3
2 e         4

控制台結果后面有一條警告消息,但它似乎對代碼行沒有任何影響。 消息如下:

Warning message:
attributes are not identical across measure variables;
they will be dropped 

暫無
暫無

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

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