【发布时间】:2021-12-27 03:48:15
【问题描述】:
我正在尝试改变一个列:
- 数据框按错误分组
- 变异列 (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