【问题标题】:Mutate by a column element based on a condition根据条件由列元素变异
【发布时间】:2021-12-27 03:48:15
【问题描述】:

我正在尝试改变一个列:

  1. 数据框按错误分组
  2. 变异列 (treatmentToGrowthRatio) 等于:

价值/(治疗==“成长”的价值)。

我有什么:

df <- tibble(
  type = as.factor(c("bug1", "bug1", "bug1", "bug2", "bug2", "bug2", "bug3", "bug3", "bug3", "blank")),
  treatment = c(rep(c("TreatA", "TreatB", "Growth"),3), "Blank"),
  value = 1:10
)

我正在执行的操作:

df %>% group_by(bug) %>% 
  mutate(
    treatmentToGrowthRatio =
      value/
      ## value where treatment == growth 
      ## (i.e. for bug 1 = 3; for bug 2 = 6; for bug 3 = 9; for Blank = NA)
  )

提供所需的输出:

dfFinal <- tibble(
  type = as.factor(c("bug1", "bug1", "bug1", "bug2", "bug2", "bug2", "bug3", "bug3", "bug3", "blank")),
  treatment = c(rep(c("TreatA", "TreatB", "Growth"),3), "Blank"),
  value = 1:10,
  treatmentToGrowthRatio = c(1/3, 2/3, 1, 4/6, 5/6, 1, 7/9, 8/9, 1, NA)
)

我得到的最接近的是treatmentToGrowthRatio = 1 where Treatment == "Growth" from:

df %>% group_by(type) %>% 
  mutate(
    treatmentToGrowthRatio =
      value/
      case_when(
        str_detect(treatment,
                   "Growth") ~ value
      )
  )

欣赏任何见解!谢谢。

【问题讨论】:

    标签: dplyr conditional-operator


    【解决方案1】:

    您的问题陈述不清楚。组 type == "blank" 没有 treatment == "Growth"。在这种情况下,您预计会发生什么?

    注意到我上面的评论,我将忽略带有type == "blank" 的行。然后你要么做

    library(dplyr)
    df %>%
        filter(type != "blank") %>%
        group_by(type) %>%
        mutate(treatmentToGrowthRatio = value / value[treatment == "Growth"]) %>%
        ungroup()
    ## A tibble: 9 x 4
    #  type  treatment value treatmentToGrowthRatio
    #  <fct> <chr>     <int>                  <dbl>
    #1 bug1  TreatA        1                  0.333
    #2 bug1  TreatB        2                  0.667
    #3 bug1  Growth        3                  1    
    #4 bug2  TreatA        4                  0.667
    #5 bug2  TreatB        5                  0.833
    #6 bug2  Growth        6                  1    
    #7 bug3  TreatA        7                  0.778
    #8 bug3  TreatB        8                  0.889
    #9 bug3  Growth        9                  1     
    

    或者(也许更优雅)从长到宽重新整形,然后从相关列中划分值。

    library(dplyr)
    library(tidyr)
    df %>%
        pivot_wider(names_from = treatment) %>%
        mutate(across(starts_with("Treat"), ~ .x / Growth))
    ## A tibble: 4 x 5
    #  type  TreatA TreatB Growth Blank
    #  <fct>  <dbl>  <dbl>  <int> <int>
    #1 bug1   0.333  0.667      3    NA
    #2 bug2   0.667  0.833      6    NA
    #3 bug3   0.778  0.889      9    NA
    #4 blank NA     NA         NA    10
    

    如有必要,然后再次整形。

    【讨论】:

    • 非常感谢!我需要回到基础 R 并进行修改。虽然我特别喜欢你的更广泛的解决方案(尤其是创造性方法)。
    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2018-02-08
    相关资源
    最近更新 更多