在 mutate 管道内查找

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

我是 R 的初学者,我真的陷入了困境。

我有一个小标题(counts_table),其中包含每个项目在数据集中重复的次数:

项目
A 6
B 3
C 3
D 3

在我的工作数据集中,我还有变量 item 以及许多其他变量。我想更改一个特定的(金额),并且我希望将其缩小,并按该项目重复的次数进行划分。

我想过在管道中使用 mutate() ,但在尝试定义某种查找函数时遇到了困难。伪代码:

  • counts_table 标题中按名称查找项目,并找到关联的计数(例如 n

  • 然后将 amount 突变为 amount / n

我真的很难定义管道内的查找。我尝试过:

df %>%
  mutate(amount = amount / counts_table[counts_table$item == item, "count"]) 

但是我收到以下错误:

✖ Logical subscript `counts_table$item == item` must be size 1 or 287, not 3768.
ℹ longer object length is not a multiple of shorter object length

当第二位单独运行时:

counts_table[counts_table$item == "string", "count"]

它确实给了我来自 counts_table tibble 的值(比如说 6),那么为什么它不将 6 应用到管道中的 mutate 函数呢?

提前致谢!

r dplyr lookup mutate
1个回答
0
投票

缺乏可重现的示例,我认为值得一试:

library(dplyr)
df |> left_join(counts_table |> select(item, count),
                .by = c(item = item)) |>
      mutate(amount = amount/count) |>
      select(-count)
© www.soinside.com 2019 - 2024. All rights reserved.