2017-10-21 57 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