2017-03-12 3 views
1

結果、私は、データフレームがtable 使用回数は()

このよう
 a m g  c1  c2  c3  c4 
1 2015 5 13 bread wine <NA> <NA>  
2 2015 8 30 wine eggs rice cake 
3 2015 1 21 wine rice eggs <NA>  
... 

と呼ばれる持っている私は、C4に列c1の要素をカウントし、それらに を注文したい私が使用してみました:

library(plyr) 
c<-count(table,"c1") 

しかし、複数の列のカウント方法はわかりません。

その後、私はそれらを注文するarrange(c,desc(freq))を使用したいが、私は1列にしようとすると、値はNAが一番上に常にある、と私は唯一のトップ3の要素をしたいです。このように

 c freq 
1 wine  3 
2 eggs  2 
3 rice  2 

誰かが私にこれのための解決策を教えてください。おかげ

+0

どのテーブル(非公開に(表[のstartsWith(名前 'について(テーブル)、 "c")])) ' –

答えて

2

使用melttableqdaptools

df1 <- read.table(text="a m g  c1  c2  c3  c4 
2015 5 13 bread wine NA NA 
2015 8 30 wine eggs rice cake 
2015 1 21 wine rice eggs NA", header=TRUE, stringsAsFactors=FALSE) 

c_col <- melt(as.matrix(df1[,4:7])) 
sort(table(c_col$value),decreasing=TRUE) 

wine eggs rice bread cake 
    3  2  2  1  1 
1

、提供されるサンプルデータフレーム(持つ名前table)を持つ:

library(qdapTools) 
counts <- data.frame(count=sort(colSums(mtabulate(table[,4:7])), decreasing=TRUE)) 
subset(counts,rownames(counts)!='<NA>')[1:3,1,drop=FALSE] #remove <NA>, select top 3 elements 

#  count 
# wine  3 
# eggs  2 
# rice  2 
関連する問題