Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用每观察值平均值(而不是行值)创建四分位列_R_Dataframe_Grouping_Quartile - Fatal编程技术网

R 使用每观察值平均值(而不是行值)创建四分位列

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

我有面板数据时间序列,我想用给定变量平均值的四分位数创建一个变量,这样一个公司只能在给定的四分位数中找到。例如,如果我有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)))

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))