2016-03-28 13 views
1

Ben Ar aşağıdaki minimum örnek var:Ar birden değişkenler/sütunlarında kategorik faktörlerin sayımlarını alın

testing = data.frame(c("Once a week", "Once a week", "Rarely", "Once a month", "Once a month"), c("Once a month", "Once a month", "Once a week", "Rarely", "Rarely")) 
colnames(testing) = c("one", "two") 
testing 

     one   two 
1 Once a week Once a month 
2 Once a week Once a month 
3  Rarely Once a week 
4 Once a month  Rarely 
5 Once a month  Rarely 

Bir sütundaki tüm olası kategorik faktörü olmayan dataframe olmak sonuçta istiyorum diğer sütunlar ise böyle her sütun/değişken için sayılar:

categories one two 
Rarely  1  2 
Once a month 2  2 
Once a week 2  1 

yüzden ne olursa olsun burada en kolay olurdu R kütüphaneleri üzerinde herhangi bir kısıtlamaya tabi (belki plyr/dplyr?).

Teşekkürler.

cevap

7

Tablo dışında paketler gerek olmadan çalışır: Bu bir matris gibi görünüyor ederken

sapply(testing, table) 
#    one two 
#Once a month 2 2 
#Once a week 2 1 
#Rarely   1 2 
+0

OP, bir data.frame talep eder. Zorlamak ya da bir şey yapmak isteyebilir. – Frank

+1

@Frank Kabul edildi. OP, istediği herhangi bir yararlı formata dönüştürebilir –

+1

Teşekkürler, etrafta bir 'as.data.frame' atacağım. :) – firefly2442

2

Sen tidyr ve dplyr paketleri ile masanızı düzenli ve başka bir yol tidyr::gather kullanan var tabanın table Burada fonksiyon

testing = data.frame(c("Once a week", "Once a week", "Rarely", "Once a month", "Once a month"), c("Once a month", "Once a month", "Once a week", "Rarely", "Rarely")) 
colnames(testing) = c("one", "two") 
testing 
#>   one   two 
#> 1 Once a week Once a month 
#> 2 Once a week Once a month 
#> 3  Rarely Once a week 
#> 4 Once a month  Rarely 
#> 5 Once a month  Rarely 

library(tidyr) 
library(dplyr) 

testing %>% 
    gather("type", "categories") %>% 
    table() 
#>  categories 
#> type Once a month Once a week Rarely 
#> one   2   2  1 
#> two   2   1  2 

# or reorder colum before table 
testing %>% 
    gather("type", "categories") %>% 
    select(categories, type) %>% 
    table() 
#>    type 
#> categories  one two 
#> Once a month 2 2 
#> Once a week 2 1 
#> Rarely   1 2 
1

ile kategorilerini güvenebileceği, tidyr::spread ve dplyr::count:

Ayrıca
library(dplyr) 
library(tidyr) 

testing %>% 
    gather(measure, value) %>% 
    count(measure, value) %>% 
    spread(measure, n) 

# Source: local data frame [3 x 3] 
# 
#   value one two 
#   (chr) (int) (int) 
# 1 Once a month  2  2 
# 2 Once a week  2  1 
# 3  Rarely  1  2 

, bunu görmek Bu konuyla ilgili fantastic gist.

İlgili konular