dplyr:将每个变量的多个`count` +`mutate`语句组合成一个语句

时间:2014-10-24 09:45:30

标签: r dplyr

拥有数据

DT = structure(list(PE_RATIO = c(NA, 18.3468544431322, 21.8536295107188, NA, NA, NA), DIVIDEND_YIELD =c(NA, NA, 0.5283019, 1.06737822831035, NA, 0.55751900359546), DollarExposure = c(6765.12578958248, 95958.3106724681, 96328.1628155842, 291638.734002894, 170983.200676477, 185115.042371833)), .Names =c("PE_RATIO", "DIVIDEND_YIELD", "DollarExposure"), row.names = c(NA, -6L), class = c("data.table","data.frame"))
DT
#    PE_RATIO DIVIDEND_YIELD DollarExposure
# 1:       NA             NA       6765.126
# 2: 18.34685             NA      95958.311
# 3: 21.85363      0.5283019      96328.163
# 4:       NA      1.0673782     291638.734
# 5:       NA             NA     170983.201
# 6:       NA      0.5575190     185115.042

我想计算多个变量(此处为PE_RATIODIVIDEND_YIELD)的可用值的加权比例(称为' Capture')。 我可以在单独的语句中做到这一点,每个变量一个语句:

DT %>% count(is.na(PE_RATIO), wt=abs(DollarExposure)) %>%
  mutate(PE_RATIO.Capture = prop.table(n))

# Source: local data table [2 x 3]
# 
# is.na(PE_RATIO)          n   PE_RATIO.Capture
# 1           FALSE 192286.5          0.2270773
# 2            TRUE 654502.1          0.7729227


DT %>% count(is.na(DIVIDEND_YIELD), wt=abs(DollarExposure)) %>%
  mutate(DIVIDEND_YIELD.Capture = prop.table(n))

# Source: local data table [2 x 3]
# 
# is.na(DIVIDEND_YIELD)          n   DIVIDEND_YIELD.Capture
# 1                 FALSE 573081.9                 0.676771
# 2                  TRUE 273706.6                 0.323229

问题

如何在单个dplyr语句中组合多个语句并在变量之间实现汇总?所需的输出如下所示:

#         is.na(variable)  DIVIDEND_YIELD.Capture   PE_RATIO.Capture
# 1                 FALSE                0.676771          0.2270773
# 2                  TRUE                0.323229          0.7729227

可能会有六个变量来计算捕获率。

1 个答案:

答案 0 :(得分:7)

尝试这样的事情

library(tidyr)
library(dplyr)
DT %>% gather(variable, value, -DollarExposure) %>% 
    group_by(variable, isna = is.na(value)) %>% 
    summarise(total = sum(abs(DollarExposure))) %>%
    group_by(variable) %>%
    mutate(prop = prop.table(total)) %>%
    ungroup %>%
    select(-total) %>%
    spread(variable, prop) 
# Source: local data frame [2 x 3]
# 
#    isna  PE_RATIO DIVIDEND_YIELD
# 1 FALSE 0.2270773       0.676771
# 2  TRUE 0.7729227       0.323229