gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:08:21 24 4
gpt4 key购买 nike

拥有数据:

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

可能有六个变量需要计算捕获率。

最佳答案

尝试这样的事情

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

关于r - dplyr:将每个变量的多个 `count` + `mutate` 语句组合成单个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26545490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com