简体   繁体   English

多列 R 中多个变量的计数

[英]Counts of multiple variables in multiple columns R

This is a sample of my data frame.这是我的数据框的示例。 Each number (1-27) represents a different reason for supporting a program.每个数字 (1-27) 代表支持计划的不同原因。

> df[10:15]
reason1  reason2  reason3  reason4  reason5  reason6
   1        2        6        13       14       27
   2        4        5        13       27       NA
   5       10       12        18       26       11
   8       27       NA        NA       NA       NA

I would like to get the total counts of each number (1-27) in the six columns (reason1-reason6).我想获得六列(reason1-reason6)中每个数字(1-27)的总数。

I'm understanding the question to be a request for a tabulation of the "reasons" values:我理解这个问题是要求列出“原因”值:

 table( unlist( df[10:15] ) )

If you need the count of NA's which seems unlikely then look at the optional parameters in ?table如果您需要看起来不太可能的 NA 计数,请查看?table的可选参数

Or if you wanted a data frame you can use dplyr, which will include NAs:或者,如果您想要一个数据框,您可以使用 dplyr,其中将包含 NA:

library(dplyr)
df[10:15] %>% gather() %>% group_by(key, value) %>% summarise(N=n()) %>% arrange(key, value)

Your result is:你的结果是:

# A tibble: 22 x 3
# Groups:   key [6]
   key     value     N
   <chr>   <chr> <int>
 1 reason1 1         1
 2 reason1 2         1
 3 reason1 5         1
 4 reason1 8         1
 5 reason2 10        1
 6 reason2 2         1
 7 reason2 27        1
 8 reason2 4         1
 9 reason3 12        1
10 reason3 5         1
# ... with 12 more rows

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM