【问题标题】:How to find the statistical mode of each ID如何找到每个ID的统计模式
【发布时间】:2021-01-16 01:38:44
【问题描述】:

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

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))

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

【问题讨论】:

  • 你得到的确切错误是什么?
  • 抱歉,它成功了,但我有一条警告消息:Warning messages: 1: Problem with `mutate()` input `edema2`. ℹ argument 'method' is missing. Data are supposed to be continuous. Default method 'shorth' is used ℹ Input `edema2` is `print(mlv(edema))`. ℹ The error occurred in group 1: id = 2. 2: argument 'method' is missing. Data are supposed to be continuous. Default method 'shorth' is used 3: Problem with `mutate()` input `edema2`.
  • 而且创建的值似乎是正确的
  • 警告说你没有提供'method'参数,所以它默认为'shorth'方法。您必须检查包作者的文档以了解其含义。 “数据应该是连续的”可能意味着您的输入值有问题

标签: r dplyr


【解决方案1】:

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

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

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

另外,为什么不使用here 中的Mode 函数:

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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多