比较列与中位数

时间:2017-02-17 22:46:00

标签: r data.table

我有一个如下数据表:

TDT <- data.table(Group = c(rep("A",40),rep("B",60)),
                      Id = c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)),
                      Date = rep(seq(as.Date("2010-01-03"), length=20, by="1 month") - 1,5),
                      x1 = sample(100,100))

我按如下方式计算x1的中位数:

TDT2 <- TDT[, median(x1), by = .(Group,Date)]

我的问题是:如何将TDT中x1的每个值与每组和日期的结果中位数进行比较?例如,如果它更低,则应该产生TRUE。我知道在Group和Date上使用嵌套for循环的一种方法,但这对于大数据集来说需要很长时间。我想知道是否有一种更可数据化的方式可能会使用by

2 个答案:

答案 0 :(得分:2)

您可以使用:=向data.table添加新列:

TDT <- data.table(Group = c(rep("A",40),rep("B",60)),
                  Id = c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)),
                  Date = rep(seq(as.Date("2010-01-03"), length=20, by="1 month") - 1,5),
                  x1 = sample(100,100))

# add median within groups
TDT[, median.x1 := as.numeric(median(x1, na.rm = T)), by = .(Group, Date)]
# compare original values to the median
TDT[, bellow.median.x1 := x1 < median.x1]

答案 1 :(得分:2)

以下是使用tidyverse

的选项
 library(tidyverse)
 TDT %>%
      group_by(Group, Id) %>%
      mutate(median_x1 = median(x1, na.rm = TRUE), below_median_x1 = x1 < median_x1)
相关问题