【发布时间】:2019-08-19 19:04:04
【问题描述】:
我正在尝试识别数据集中特定变量值不同的组。
例如,在下面的数据中,我有四个病人,每个人预约了三个时间。
dat <- structure(list(patient = c('John', 'John', 'John', 'Jean', 'Jean', 'Jean', 'Jack', 'Jack', 'Jack', 'Jess', 'Jess', 'Jess'),
status = c('Well', 'Well', 'Well', 'Well', 'Sick', 'Well', 'DNA', 'DNA', 'DNA', 'DNA', 'Well', 'Well')), class = "data.frame", row.names = c(NA, -12L))
有时他们很好,有时生病,有时他们没有参加(DNA)。
我可以很容易地看到,至少其中一些的状态在约会之间有所不同:
nrow(unique(dat)) == length(unique(dat$patient))
# gives FALSE
我正在尝试找出如何识别哪些患者具有不同的状态。
目前为止我最好的是:
# function to find if all elements of a vector are the same
all_same <- function(x) all(x == x[1])
# split table and apply function
sapply(split(dat$status, dat$patient), all_same)
这可行,但我有一个包含许多组(即患者)的大型数据集。我似乎经常遇到这个特定的问题。我觉得必须有一种优雅和矢量化的方式来做到这一点。我知道我可以使用 dplyr/data.table 提高我的方法的速度,但我只能想到拆分数据然后在组上循环一个函数的方法。最好的方法是什么?
【问题讨论】:
标签: r performance loops vectorization