简体   繁体   English

从R中的data.table列计算中位数

[英]calculate median from data.table columns in R

I am trying to calculate a median value across a number of columns, however my data is a bit funky. 我试图计算多个列的中值,但我的数据有点时髦。 It looks like the following example. 它看起来像下面的例子。

library(data.table)

dt <- data.table("ID" = c(1,2,3,4),"none" = c(0,5,5,3), 
                 "ten" = c(3,2,5,4),"twenty" = c(0,2,3,1))


   ID none ten twenty
1:  1    0   3      0
2:  2    5   2      2
3:  3    5   5      3
4:  4    3   4      1

In the table to column represents the number of occurrences of that value. 在表中,列表示该值的出现次数。 I am wanting to calculate the median occurrence. 我想计算中位数。

For example for ID = 1 例如,对于ID = 1

median(c(10, 10, 10))

is the calculation I am wanting to create. 是我想要创建的计算。

for ID = 2 对于ID = 2

median(c(0, 0, 0, 0, 0, 10, 10, 20, 20))

I have tried using rep() and lapply() with very limited success and am after some clear guidance on how this might be achieved. 我尝试过使用rep()lapply()取得了非常有限的成功,并且已经明确指出了如何实现这一目标。 I understand for the likes of rep() I would be having to hard code my value to be repeated (eg rep(0,2) or rep(10,2) ) and this is what I expect. 我理解为rep()我将不得不硬编码我的值重复(例如rep(0,2)rep(10,2) ),这就是我所期望的。 I am just struggling to create a list or vector with the repetitions from each column. 我正在努力创建一个包含每列重复的列表或向量。

Here's another data.table way (assuming unique ID ): 这是另一种data.table方式(假设唯一ID ):

dt[, median(rep(c(0, 10, 20), c(none, ten, twenty))), by=ID]
#    ID V1
# 1:  1 10
# 2:  2  0
# 3:  3 10
# 4:  4 10

This is just an attempt to get @eddi's answer without reshaping (which I tend to use as a last resort). 这只是试图获得@ eddi的答案而不重塑(我倾向于使用它作为最后的手段)。

You need a dictionary to translate column names to corresponding numbers, and then it's fairly straightforward: 您需要一个字典来将列名转换为相应的数字,然后它非常简单:

dict = data.table(name = c('none', 'ten', 'twenty'), number = c(0, 10, 20))

melt(dt, id.var = 'ID')[
  dict, on = c(variable = 'name')][, median(rep(number, value)), by = ID]
#   ID V1
#1:  1 10
#2:  2  0
#3:  3 10
#4:  4 10

Here's a way that avoids by-row operations and reshaping: 这是一种避免行间操作和重新整形的方法:

dt[, m := {
    cSD  = Reduce(`+`, .SD, accumulate=TRUE)
    k    = floor(cSD[[length(.SD)]]/2)

    m    = integer(.N)
    for(i in seq_along(cSD)) {
        left = m == 0L
        if(!any(left)) break
        m[left] = i * (cSD[[i]][left] >= k[left])
    }
    names(.SD)[m]
}, .SDcols=none:twenty]

which gives 这使

   ID none ten twenty    m
1:  1    0   3      0  ten
2:  2    5   2      2 none
3:  3    5   5      3  ten
4:  4    3   4      1  ten

For the loop, I'm borrowing @alexis_laz' style, eg https://stackoverflow.com/a/30513197/ 对于循环,我借用@alexis_laz'样式,例如https://stackoverflow.com/a/30513197/

I've skipped translation of the column names, but that's pretty straightforward. 我已经跳过了列名的翻译,但这非常简单。 You could use c(0,10,20) instead of names(.SD) at the end. 您最后可以使用c(0,10,20)而不是names(.SD)

Here is a rowwise dplyr way: 这里是一个rowwise dplyr方式:

dt %>% rowwise %>% 
       do(med = median(c(rep(0, .$none), rep(10, .$ten), rep(20, .$twenty)))) %>%  
       as.data.frame
  med
1  10
2   0
3  10
4  10

Inspired by @Arun's answer, this is also working: 受@ Arun的回答启发,这也有效:

dt %>% group_by(ID) %>% 
       summarise(med = median(rep(c(0, 10, 20), c(none, ten, twenty))))

Source: local data table [4 x 2]

     ID   med
  (dbl) (dbl)
1     1    10
2     2     0
3     3    10
4     4    10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM