【发布时间】:2018-05-11 21:23:51
【问题描述】:
我正在尝试对数据框行应用 Hmisc wdt.mean 函数。它通常需要两个向量,一个用于平均值,一个用于平均值的权重。我试图找到一个dplyr/tidyr/purrr 解决方案,但无法完全弄清楚。
library(Hmisc)
#build data frame with 10 weight columns and 10 mean columns
set.seed(10)
w = matrix(runif(200,0,1),ncol = 20)
w = w/rowSums(w)
m = matrix(runif(200,50,100),ncol = 20)
df <- as.data.frame(cbind(w,m))
colnames(df) <- c(paste0("weight",seq(1,20,1)),paste0("mean",seq(1,20,1)))
# calculate weighted means for each row
for (i in 1:nrow(df)) {
df$weighted.means [i] <- wtd.mean(x =as.numeric(df[i,21:40]), weights = as.numeric(df[i,1:20]) )
}
> df$weighted.means
[1] 70.74705 82.85015 82.40826 73.35798 70.02986 74.05543 73.64709 77.12899 72.56236 84.74055
【问题讨论】:
-
你可以做
apply(df, 1, function(x) wtd.mean(x =as.numeric(x[21:40]), weights = as.numeric(x[1:20]))),但这不是那么漂亮,也不是tidyverse。 -
我想
dplyr::mutate我在底部显示的 weighted.means 列而不使用 for 循环。
标签: r