基于多个级别的多个变量计算大型数据框的权重

问题描述 投票:0回答:1

我需要根据两个不同的变量计算我的大数据框的一些权重。假设它们是

x = c("a","b","c","d","e")
y = c("v","w","x","y","z")
。这两个变量有 25 种不同的组合。

我将使用的权重取决于

x
y
每个级别在我的数据框中出现的频率。所以可能是“a”出现 34% 的时间,“b”出现 12% 的时间,等等。假设我已将这些比例的值保存到
x_prop
y_prop
。我的体重是通过
x
级别除以
y
级别的比例来计算的。

我的问题是,有没有更好、更有效的方法来解决这个问题,而不是用类似的暴力方法:

weights <- c()
for (i in 1:nrow(df)){
  if (df$x[i] == "a" & df$y[i] == "v"){weights[i] <- (x_prop[1] / y_prop[1])}
  else if (df$x[i] == "a" & df$y[i] == "w"){weights[i] <- (x_prop[1] / y_prop[2])}
  ...
  else if (df$x[i] == "e" & df$y[i] == "z"){weights[i] <- (x_prop[5] / y_prop[5])}
}

我实际上需要对变量的多种组合执行此操作。对单个对执行此操作会导致 25 行带有这些 if 语句的相当冗余的代码,我忍不住认为有很多更有效的方法来做到这一点。

有什么建议吗?

编辑:我的数据框如下所示:

df <- data.frame(x = c("a", "a", "c", "e", "e", "b", "a", "d"),
                 y = c("v", "w", "z", "x", "x", "x", "y", "v"))

那里还有其他变量(实际上,我的数据框有数千个数据点),但我需要做的是根据 x 和 y 的每种可能的组合对另一个变量采取行动。

r loops weighted
1个回答
0
投票

实现此目的的一种方法是制作一个查找表,其中包含所有可能的 x/y 组合及其各自的权重。

df <- data.frame(x = c("a", "a", "c", "e", "e", "b", "a", "d"),
                 y = c("v", "w", "z", "x", "x", "x", "y", "v"))

library(dplyr)
lookup <- tidyr::crossing(
  count(df, x) |> transmute(x, x_share = n / sum(n)),
  count(df, y) |> transmute(y, y_share = n / sum(n))) |>
  mutate(weight = x_share / y_share)

df |>
  left_join(lookup)


Joining with `by = join_by(x, y)`
  x y x_share y_share    weight
1 a v   0.375   0.250 1.5000000
2 a w   0.375   0.125 3.0000000
3 c z   0.125   0.125 1.0000000
4 e x   0.250   0.375 0.6666667
5 e x   0.250   0.375 0.6666667
6 b x   0.125   0.375 0.3333333
7 a y   0.375   0.125 3.0000000
8 d v   0.125   0.250 0.5000000
© www.soinside.com 2019 - 2024. All rights reserved.