根据另一个向量中的ID逐行求和列

时间:2017-05-04 14:22:28

标签: r dataframe aggregate

我有两个输入数据框,第一个叫做“Firms_Ind”,包含多行的2列(“Firms”,“Industry”)。它为每个公司提供行业ID。另一个被称为“ann_returns”,它具有与“Firms_Ind”一样多的列具有行和多行。它包含每年(行)每个公司(列)的回报。

我想计算每个行业的年平均回报率。所以我想要一个输出矩阵,它具有以下维度:列数=年数和行数=年数。对于每个行业(列),应计算每年的平均收益。

这是一个小例子:

> Firms_Ind
  Firms Industry
1     A        1
2     B        2
3     C        3
4     D        1
5     E        2
6     F        1

> ann_returns
      A    B    C    D    E    F
y1 0.20 0.11 0.13 0.30 0.24 0.03
y2 0.23 0.08 0.03 0.23 0.17 0.01
y3 0.28 0.19 0.11 0.21 0.19 0.07

> Industry_mean
            1    2    3
y1_means 0.20 0.11 0.13
y2_means 0.23 0.08 0.03
y3_means 0.28 0.19 0.11

3 个答案:

答案 0 :(得分:1)

以下是sapply

的一种方法
# get a list of firms by industry
inds <- split(Firms_Ind$Firms, Firms_Ind$Industry)
# loop through industries to calculate annual means
myMat <- sapply(inds,
              function(i) if(length(i) > 1) rowMeans(ann_returns[, i]) else ann_returns[, i])

在这里,sapply遍布各个行业。对于每个行业,检查是否有多家公司,如果是,则应用rowMeans,如果不是,则返回原始值。

返回

myMat
           1     2    3
y1 0.1766667 0.175 0.13
y2 0.1566667 0.125 0.03
y3 0.1866667 0.190 0.11

数据

Firms_Ind <-
structure(list(Firms = structure(1:6, .Label = c("A", "B", "C", 
"D", "E", "F"), class = "factor"), Industry = c(1L, 2L, 3L, 1L, 
2L, 1L)), .Names = c("Firms", "Industry"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

ann_returns <- 
structure(c(0.2, 0.23, 0.28, 0.11, 0.08, 0.19, 0.13, 0.03, 0.11, 
0.3, 0.23, 0.21, 0.24, 0.17, 0.19, 0.03, 0.01, 0.07), .Dim = c(3L, 
6L), .Dimnames = list(c("y1", "y2", "y3"), c("A", "B", "C", "D", 
"E", "F")))

答案 1 :(得分:1)

使用location.searchdplyr

tidyr

答案 2 :(得分:1)

我们可以按行拆分ann_returns,然后运行rowMeans

# if Firms in correct order
inds <- split.default(ann_returns, f = Firms_Ind$Industry)

# # if Firms not in correct order:
# inds <- split.default(
#     ann_returns,
#     f = Firms_Ind$Industry[match(colnames(ann_returns), Firms_Ind$Firms)])

do.call(cbind, lapply(inds,rowMeans))
#            1     2    3
# y1 0.1766667 0.175 0.13
# y2 0.1566667 0.125 0.03
# y3 0.1866667 0.190 0.11

两个输入data.frames是:

# > dput(ann_returns)
structure(list(A = c(0.2, 0.23, 0.28), B = c(0.11, 0.08, 0.19
), C = c(0.13, 0.03, 0.11), D = c(0.3, 0.23, 0.21), E = c(0.24, 
0.17, 0.19), F = c(0.03, 0.01, 0.07)), .Names = c("A", "B", "C", 
"D", "E", "F"), row.names = c("y1", "y2", "y3"), class = "data.frame")
# > dput(Firms_Ind)
structure(list(Firms = structure(1:6, .Label = c("A", "B", "C", 
"D", "E", "F"), class = "factor"), Industry = c(1L, 2L, 3L, 1L, 
2L, 1L)), .Names = c("Firms", "Industry"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))