使用每次观察的平均值而不是行值创建四分位数列

Creating a Quartile Column using average per observations instead as row value

我有面板数据时间序列,我想用给定变量的平均值的四分位数创建一个变量,以便只能在给定的四分位数中找到一家公司。例如,如果我有 4 家公司:

 df = 
    id year value Quartile* Quartile**
    1  2010 1      1         1
    1  2015 1      1         1
    2  2010 10     2         2  
    2  2015 10     2         2
    3  2010 10     2         3
    3  2015 20     3         3
    4  2010 40     4         4
    4  2015 40     4         4

使用标准方法四分位数* 例如:

df<- within(df, Quartile* <- as.integer(cut(TotalAssets_wins,
                                            quantile(value, probs=0:4/4), 
                                            include.lowest=TRUE)))

我获得了 Quartile* 的值,但是,我想防止公司随着时间的推移具有不同的四分位数值。出于这个原因,我想根据每家公司所有观察值的平均值来计算四分位数的值,以获得四分位数**的值。关键区别在于它们是公司依赖的价值观。知道如何在我的代码中实现它吗?

这是使用 tapplyranksplit 的一种方法。

# create 0 vector
dat$q <- 0
# fill it in
split(dat$q, dat$id) <- rank(tapply(dat$value, dat$id, FUN=mean))

这里,tapply通过ID计算均值,rank对这些均值进行排序。我们使用 split 将此排名输入 data.frame 的列 q。作为旁注,因为 tapplysplit 将以相同的顺序将观察结果排列到相同的组中,所以观察结果不必按照任何特定的顺序进行。

这个returns

dat
  id year value Quartile. Quartile.. q
1  1 2010     1         1          1 1
2  1 2015     1         1          1 1
3  2 2010    10         2          2 2
4  2 2015    10         2          2 2
5  3 2010    10         2          3 3
6  3 2015    20         3          3 3
7  4 2010    40         4          4 4
8  4 2015    40         4          4 4

其中 q 列与 Quartile.. 列中的所需值匹配。

数据

dat <-
structure(list(id = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), year = c(2010L, 
2015L, 2010L, 2015L, 2010L, 2015L, 2010L, 2015L), value = c(1L, 
1L, 10L, 10L, 10L, 20L, 40L, 40L), Quartile. = c(1L, 1L, 2L, 
2L, 2L, 3L, 4L, 4L), Quartile.. = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 
4L)), .Names = c("id", "year", "value", "Quartile.", "Quartile.."
), class = "data.frame", row.names = c(NA, -8L))