【问题标题】:apply function taking two vectors over data frame rows在数据框行上应用两个向量的函数
【发布时间】: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


【解决方案1】:

你可以这样做:

df %>% 
  mutate(weighted.means = apply(df, 1, function(x) wtd.mean(x = as.numeric(x[21:40]), 
                                                            weights = as.numeric(x[1:20]))))

或使用这个(长...)tidyverse 解决方案:

df %>% 
  rownames_to_column("group") %>% 
  gather(name, value, -group) %>% 
  extract(name, into = c("weight_mean", "number"), regex = "([[:alpha:]]+)(\\d+)") %>% 
  spread(weight_mean, value) %>% 
  group_by(group = as.numeric(group)) %>% 
  summarise(weighted.means = wtd.mean(x = mean, weights = weight))

# A tibble: 10 x 2
#    group weighted.means
#    <dbl>          <dbl>
#  1 1               70.7
#  2 2               82.9
#  3 3               82.4
#  4 4               73.4
#  5 5               70.0
#  6 6               74.1
#  7 7               73.6
#  8 8               77.1
#  9 9               72.6
# 10 10              84.7

【讨论】:

  • 您的解决方案确实有效。谢谢。我必须在最后添加几行将“组”转换为数字并安排以正确的顺序获取手段。
  • 我解决了这个问题 ;)
猜你喜欢
  • 1970-01-01
  • 2018-12-13
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 2019-01-30
  • 2011-04-08
相关资源
最近更新 更多