简体   繁体   English

使用数据子集时如何创建新列并计算data.table中的中位数

[英]How to create new column and calculate median in data.table when using a subset of data

Hi I have a data like this: 嗨,我有这样的数据:

  date    type    data
198101       1     0.1
198101       1     0.3
198101       2     0.5
198102       1     1.2
198102       1     0.9
198102       2     0.7
198102       2     0.3

I would like to create a new column to show the median each month according to criteria when type == 1. 我想创建一个新列,以在类型== 1时根据条件显示每月的中位数。

The result I would like to be is like this 我想要的结果是这样的

  date    type    data    P50
198101       1     0.1    0.2
198101       1     0.3    0.2
198101       2     0.5    0.2
198102       1     1.2   1.05
198102       1     0.9   1.05
198102       2     0.7   1.05
198102       2     0.3   1.05

currently I do it this way, lets call the above data.table as dt 目前我是用这种方式,让我们将上面的data.table称为dt

dt.median = dt[type == 1]
dt.median = dt.median[, .(P50 = median(data)), by=.(date)]

Then merge it back into the original dt 然后将其合并回原始dt

dt = dt[dt.median, nomatch = 0, by=.(date)]

Is there a quicker way to do this using .SD or .SDcol? 是否有使用.SD或.SDcol的更快方法? I want to practice using .SD but just cannot figure it out with maybe one line of code? 我想练习使用.SD,但可能无法用一行代码来解决?

What I could think of is currently 我现在能想到的

dt[, P50 := * .SD[type == 1] ...  * , by =.(date)]

but then I dont know what the syntax to put in to calculate median * .SD[type == 1] ... *, 但后来我不知道要使用什么语法来计算中位数* .SD [type == 1] ... *,

Help will be much appreciated! 帮助将不胜感激!

Just index the data values within groups using a logical vector and assign with the data.table special assignment operator, := 只需使用逻辑向量为组内的数据值编制索引,并使用data.table特殊赋值运算符:=

> dt[ , P50 := median(data[type==1]), by=.(date)]
> dt
     date type data  P50
1: 198101    1  0.1 0.20
2: 198101    1  0.3 0.20
3: 198101    2  0.5 0.20
4: 198102    1  1.2 1.05
5: 198102    1  0.9 1.05
6: 198102    2  0.7 1.05
7: 198102    2  0.3 1.05

From base R 从基数R

v=dt$data
v[dt$type!=1]=NA
ave(v,dt$date,FUN=function(x) median(x,na.rm=T))
[1] 0.20 0.20 0.20 1.05 1.05 1.05 1.05

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

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