r - 如何找到每个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
...。
解决方案
您收到的警告暗示了两件事。
您尚未指定
method
选择什么,因此使用默认方法“shorth”。这表明模式值的选择存在关联。
或者,为什么不使用这里Mode
的功能:
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
要按组申请,您可以将其与dplyr
as 一起使用:
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
推荐阅读
- apache-spark - 写入配置单元分区时,Spark 暂存目录竞争条件?
- python - 在 Python 中查找数据框日期列和参考日期之间的时间
- java - 使用springboot rest客户端发送多部分请求总是给出400 BAD_REQUEST错误
- javascript - 我们可以合并覆盖报告 Jest 和 Mocha 吗?
- 32bit-64bit - 将 32 位移植到 64 位 C 程序“抛出异常:读取访问冲突 0xC0000005”
- html - 负 CSS 悬停链接
- c# - 如果一个字符串有阿拉伯语单词,那么它必须从 wpf 中的“RTL”写入,即字符串的方向
- react-native - 标题下的渐变
- node.js - 无法在终端上使用 psql 命令访问在 docker 容器内运行的 postgres
- java - Java ClassCastException 使用时?延伸