R 使用每观察值平均值(而不是行值)创建四分位列
我有面板数据时间序列,我想用给定变量平均值的四分位数创建一个变量,这样一个公司只能在给定的四分位数中找到。例如,如果我有4家公司:R 使用每观察值平均值(而不是行值)创建四分位列,r,dataframe,grouping,quartile,R,Dataframe,Grouping,Quartile,我有面板数据时间序列,我想用给定变量平均值的四分位数创建一个变量,这样一个公司只能在给定的四分位数中找到。例如,如果我有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
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)))
df这里有一种使用taply
、rank
和split
的方法
# create 0 vector
dat$q <- 0
# fill it in
split(dat$q, dat$id) <- rank(tapply(dat$value, dat$id, FUN=mean))
其中,q列与四分位数中的所需值匹配。。专栏
数据
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))
dat
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))