确定观察结果不同的人群

时间:2019-03-28 21:41:20

标签: r performance loops vectorization

我正在尝试识别数据集中特定变量值不同的组。

例如,在下面的数据中,我有4位患者,并进行了3次约会。

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来提高我的方法的速度,但是我只能想到的方法是拆分数据,然后在组上循环一个函数。最好的方法是什么?

4 个答案:

答案 0 :(得分:3)

这是一种不整洁的方式:

table(unique(dat)[,'patient'])

给予

Jack Jean Jess John 
  1    2    2    1 

答案 1 :(得分:1)

另一种稍微整齐的方法是保存有关状态的信息:

library("tidyverse")

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

dat %>% 
  # Keep unique combinations of patient and status
  distinct(patient, status) %>%
  # Are they are any patients with more than one status?
  group_by(patient) %>%
  filter(n() > 1) %>%
  summarise(status=paste(status, collapse = ","))
#> # A tibble: 2 x 2
#>   patient status   
#>   <chr>   <chr>    
#> 1 Jean    Well,Sick
#> 2 Jess    DNA,Well

reprex package(v0.2.1)于2019-03-28创建

答案 2 :(得分:1)

这是一个data.table方法

 library(data.table)
 setDT(dat); 
 dat[,.(unique=uniqueN(status)),patient]

   patient unique
1:    John      1
2:    Jean      2
3:    Jack      1
4:    Jess      2

答案 3 :(得分:0)

这是一个主意...

d <- function (x) { # test whether each element of a vector is different to the element before
  y <- x != c(x[-1], NA)
  y <- c(F, y)
  y[-length(y)]
}

dat$nc <- d(dat$status) & !d(dat$patient) # status changes but patient doesn't
unique(dat$patient[dat$nc])

编辑-这是我第一次进行基准测试

结果表明,为此目的,base的split / apply和'table'方法实际上比dplyr或data.table都快,而'ch'函数则要快得多。 “ ch”功能确实依赖于患者位于表中的连续行上,而其他方法则没有。

# function for my approach above

ch <- function(dat, group, status) {
  d <- function (x) {
    y <- x != c(x[-1], NA)
    y <- c(F, y)
    y[-length(y)]
  }
  unique(dat[,group][d(dat[,status]) & !d(dat[,group])])
}

# you can also use factor and diff - see 'ch2' below
# generate data with 20000 groups

library(stringi)
dat <- data.frame(patient = rep(stri_rand_strings(20000, 7), each = 4),
                  status = sample(c('A', 'B', 'C'), 80000, replace = T, prob = c(0.8, 0.1, 0.1)),
                  stringsAsFactors = F)

microbenchmark(
  dplyr = dat %>% as_tibble() %>% group_by(patient) %>% summarise(result = n_distinct(status)),
  split_apply =  sapply(split(dat$status, dat$patient), function(x) all(x == x[1])),
  table = table(unique(dat)[,'patient']),
  ch = ch(dat, 'patient', 'status'),
  ch2 = unique(dat$patient[c(F, diff(as.numeric(factor(dat$patient))) != 0 & diff(as.numeric(factor(dat$status))) == 0)]),
  datatable = {setDT(dat); dat[,.(unique=uniqueN(status)),patient]},
  times = 1
)

Unit: milliseconds
        expr       min        lq      mean    median        uq       max neval
       dplyr 5523.6048 5523.6048 5523.6048 5523.6048 5523.6048 5523.6048     1
 split_apply  165.8760  165.8760  165.8760  165.8760  165.8760  165.8760     1
       table  224.9030  224.9030  224.9030  224.9030  224.9030  224.9030     1
          ch   10.8821   10.8821   10.8821   10.8821   10.8821   10.8821     1
         ch2  146.2358  146.2358  146.2358  146.2358  146.2358  146.2358     1
   datatable  851.1028  851.1028  851.1028  851.1028  851.1028  851.1028     1
相关问题