2017-10-21 56 views
1

如果您想要查找數據框中每列的最大頻率並返回因子,類別和頻率,您會做什麼?數據框中每列最常見

所以我的代碼如下:

dfreqcommon = data.frame() 

for (i in 1:ncol(diamonds)){ 

dfc = data.frame(t(table(diamonds[,i]))) 
dfc$Var1 = names(diamonds)[i] 

dfreqcommon = rbind(dfreqcommon, dfc) 

} 

names(dfreqcommon) = c("Factors","Categories","Frequency") 

dfreqcommon 

但這似乎返回所有因素,類別和頻率。我只是想要每個因素的最大頻率,並獲得它的類別。我試圖將dfc更改爲

dfc = data.frame(max(t(table(diamonds[,i])))) 

但它沒有顯示類別。有沒有什麼辦法解決這一問題?

回答

1

你的意思是你想得到類似這樣的結果嗎?以下示例顯示瞭如何獲取ggplot2::diamonds數據集中每列的最頻繁出現的值。

library(dplyr) 
library(tidyr) 
ggplot2::diamonds %>% 
    mutate_all(as.character) %>% 
    gather(varname, value) %>% 
    count(varname, value) %>% 
    group_by(varname) %>% 
    arrange(desc(n), .by_group = TRUE) %>% 
    slice(1) 

#> # A tibble: 10 x 3 
#> # Groups: varname [10] 
#> varname value  n 
#>  <chr> <chr> <int> 
#> 1 carat 0.3 2604 
#> 2 clarity SI1 13065 
#> 3 color  G 11292 
#> 4  cut Ideal 21551 
#> 5 depth 62 2239 
#> 6 price 605 132 
#> 7 table 56 9881 
#> 8  x 4.37 448 
#> 9  y 4.34 437 
#> 10  z 2.7 767 
+0

是的,它僅適用於鑽石的數據集,但我想的只是測試了這一點,對鑽石,然後將其用於其他數據幀也是如此。你已經返回了我想要的東西,但是我想將它的值部分添加到我的整體函數中,以便它可以用於其他數據集以及... –

2

的另一種方式,與base R:

library(ggplot2) # only to get the diamonds data.frame 

data.frame(Factors=colnames(diamonds), 
      t(sapply(diamonds, # apply following function to each column 
        function(x) { 
         t_x <- sort(table(x), decreasing=TRUE) # get the frequencies and sort them in decreasing order 
         list(Categories=names(t_x)[1], # name of the value with highest frequency 
          Frequency=t_x[1]) # highest frequency 
        }))) 
#  Factors Categories Frequency 
#carat  carat  0.3  2604 
#cut   cut  Ideal  21551 
#color  color   G  11292 
#clarity clarity  SI1  13065 
#depth  depth   62  2239 
#table  table   56  9881 
#price  price  605  132 
#x    x  4.37  448 
#y    y  4.34  437 
#z    z  2.7  767