公式结构中可以有多个响应变量吗?

时间:2019-04-12 02:16:51

标签: r

除了使用公式而不是SyncronizationContextx

之外,我想复制这段代码。
by

我尝试了此assets <- data.frame(asset.class = c("equity", "equity","equity", "option","option","option", "bond", "bond"), rating = c("AAA", "A", "A", "AAA", "BB", "BB", "AAA", "A"), counterparty.a = c(runif(3), rnorm(5)), counterparty.b = c(runif(3), rnorm(5)), counterparty.c = c(runif(3), rnorm(5))) aggregate(x = assets[c("counterparty.a", "counterparty.b", "counterparty.c")], by = assets[c("asset.class", "rating")], FUN = sum) ,但没有成功。如何添加多个响应变量?

1 个答案:

答案 0 :(得分:1)

我们可以使用cbind

out1 <- aggregate(cbind(counterparty.a, counterparty.b,  counterparty.c) ~ 
             asset.class + rating, assets, sum)

或指定.以包括所有其他列

out2 <- aggregate(.~ asset.class + rating, assets, sum)
identical(out1, out2)
#[1] TRUE

使用tidyverse

可以更轻松地完成此操作
library(dplyr)
assets %>%
      group_by_at(1:2) %>%
      summarise_all(sum)

当我们在+的{​​{1}}上进行lhs时,它通过将组内水平和垂直折叠的行与下面的行类似地折叠成单个列

~