2017-10-20 175 views
1

我想计算分类变量的最频繁值。我尝试使用modeest软件包中的mlv函数,但获得了NAs。R中的分类变量的统计模式(使用mlv)

user <- c("A","B","A","A","B","A","B","B") 
color <- c("blue","green","blue","blue","green","yellow","pink","blue") 
df <- data.frame(user,color) 
df$color <- as.factor(df$color) 

library(plyr) 
library(dplyr) 
library(modeest) 

summary <- ddply(df,.(user),summarise,mode=mlv(color,method="mlv")[['M']]) 

Warning messages: 
1: In discrete(x, ...) : NAs introduced by coercion 
2: In discrete(x, ...) : NAs introduced by coercion 

summary 
    user mode 
1 A NA 
2 B NA 

然而,我需要这样的:

user mode 
A  blue 
B  green 

我在做什么错?我尝试过使用其他方法,以及mlv(x=color)。根据modeest的帮助页面,它应该适用于各种因素。

我不想使用table(),因为我需要一个简单的函数来创建一个类似于这个问题的汇总表:How to get the mode of a group in summarize in R,但是对于一个分类列。

+1

也许还有相关性:[*“是否有内置函数用于查找模式?”](https://stackoverflow.com/q/2547402/2204410) – Jaap

回答

0

原因modeest::mlv.factor()不起作用可能实际上是包中的一个错误。

在函数mlv.factor()中调用函数modeest:::discrete()。在那里,这是发生了什么:

f <- factor(color) 
[1] blue green blue blue green yellow pink blue 
Levels: blue green pink yellow 

tf <- tabulate(f) 
[1] 4 2 1 1 

as.numeric(levels(f)[tf == max(tf)]) 
[1] NA 
Warning message: 
NAs introduced by coercion 

这是返回到mlv.fator()。但levels(f)[tf == max(tf)]等于[1] "blue",因此as.numeric()无法将其转换为数字。

您可以通过查找唯一值并计算它们出现在向量中的次数来计算模式。然后,您可以子集唯一值出现最爱的人(即模式)

找到独特的颜色:

unique_colors <- unique(color) 

match(color, unique_colors)返回colorunique_colors第一场比赛的位置。 tabulate()然后计算出现颜色的次数。 which.max()返回最高发生值的索引。这个值然后可以被用于子集独特的颜色。

unique_colors[which.max(tabulate(match(color, unique_colors)))] 

或许更具可读性使用dplyr

library(dplyr) 
unique(color)[color %>% 
       match(unique(color)) %>% 
       tabulate() %>% 
       which.max()] 

返回这两个选项:

[1] blue 
Levels: blue green pink yellow 

编辑:

可能是创建自己的模式功能的最佳方式:

calculate_mode <- function(x) { 
    uniqx <- unique(x) 
    uniqx[which.max(tabulate(match(x, uniqx)))] 
} 

,然后用它在dplyr::summarise()

library(dplyr) 

df %>% 
    group_by(user) %>% 
    summarise(color = calculate_mode(color)) 

将返回:

# A tibble: 2 x 2 
    user color 
    <fctr> <fctr> 
1  A blue 
2  B green 
+0

感谢您的详细解释!我现在明白了为什么mlv不起作用。但是,我提供的例子只是一个示例问题。我实际上想要计算我的庞大数据库中另一列的每个唯一值的模式值(大约100万个样本,10000个唯一值),也许使用dplyr :: summarize ..还有什么我可以用来计算模式的功能性的方式? – cantordust

+0

我已将示例更改为更能反映我的问题。 – cantordust

+0

非常感谢Clemens!将按照您的建议创建该功能。我想避免这样做,因为我觉得它可能效率低下,但似乎是目前唯一的选择。奇怪的是像R这样的统计工具没有内置模式计算器。 – cantordust

1

你应该尝试table。例如,which.max(table(color))

+0

感谢您的提示!这只是一个简单的例子问题。我实际上想要计算我的庞大数据库中另一列的每个唯一值的模式值(大约100万个样本,10000个唯一值),也许使用dplyr :: summarize ..还有什么我可以用来计算模式的功能性的方式? – cantordust

+0

我已将示例更改为更能反映我的问题。 – cantordust