【问题标题】:Mutate to add column based on values in another column?变异以根据另一列中的值添加列?
【发布时间】:2020-12-13 12:05:16
【问题描述】:

我有两列 - “end_use_type”和“tonnes”。我正在尝试制作第三列,其值来自“tonnes”,但仅适用于“end_use_type”为“Discards”的行。新列将命名为“tonnes_discards”。

我想我想使用 mutate 函数,但不知道如何实际选择 Discards 的值。

这是我目前所拥有的,数量不多,甚至可能都不对。

  select(c(end_use_type, tonnes)) %>% 
  mutate()

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: r dplyr


【解决方案1】:

你可能想要case_when

尝试:

select(end_use_type, tonnes) %>%
    mutate(tonnes_discards = case_when(end_use_type == 'Discards' ~ tonnes, TRUE ~ NA_Character)

当 end_use_type 等于 'Discards' 时(注意大写),该代码将 values 吨列复制到新的 tons_discards 列中。当它不等于'Discards'时,它插入一个NA。您可以将 NA_Character 替换为您想要的任何内容(可能为零?)。

如果遇到困难,请查看 dplyr case_when 帮助文件,但应该没问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2021-03-23
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多