首页 > 解决方案 > 如何找到每个ID的统计模式

问题描述

这是我的数据集中两个人的观察结果。

data=structure(list(id = c(2L, 2L, 2L, 3L, 3L, 3L), trt = c(1L, 1L, 
1L, 1L, 1L, 1L), status = c(0L, 0L, 0L, 2L, 2L, 2L), stage = c(3L, 
3L, 3L, 4L, 4L, 4L), spiders = c(1L, 1L, 1L, 0L, 1L, 0L), sex = structure(c(2L, 
2L, 2L, 1L, 1L, 1L), .Label = c("m", "f"), class = "factor"), 
    hepato = c(1L, 1L, 1L, 0L, 1L, 0L), edema = c(0, 0, 0, 0.5, 
    0, 0.5), ascites = c(0L, 0L, 0L, 0L, 0L, 0L)), row.names = c(NA, 
-6L), class = "data.frame")

我想在分组后计算每个人的统计模式id。我在下面使用了这段代码:

library(dplyr)
library(modeest)

    data%>%
      group_by(id)%>%mutate(edema2=mlv(edema))

在计算模式时我收到​​一条错误消息,而此方法适用于其他统计参数,例如mean, sd, min, max...。

标签: rdplyr

解决方案


您收到的警告暗示了两件事。

  1. 您尚未指定method选择什么,因此使用默认方法“shorth”。

  2. 这表明模式值的选择存在关联。

或者,为什么不使用这里Mode的功能:

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

要按组申请,您可以将其与dplyras 一起使用:

library(dplyr)
data%>% group_by(id)%>% mutate(edema2= Mode(edema))

#     id   trt status stage spiders sex   hepato edema ascites edema2
#  <int> <int>  <int> <int>   <int> <fct>  <int> <dbl>   <int>  <dbl>
#1     2     1      0     3       1 f          1   0         0    0  
#2     2     1      0     3       1 f          1   0         0    0  
#3     2     1      0     3       1 f          1   0         0    0  
#4     3     1      2     4       0 m          0   0.5       0    0.5
#5     3     1      2     4       1 m          1   0         0    0.5
#6     3     1      2     4       0 m          0   0.5       0    0.5

推荐阅读