gpt4 book ai didi

r - R 中列的条件计算

转载 作者:行者123 更新时间:2023-12-02 18:45:25 25 4
gpt4 key购买 nike

我有以下数据:

pop.2017 <- c(434,346,345,357)
pop.2018 <- c(334,336,325,345)
pop.2019 <- c(477,346,145,345)
pop.2020 <- c(474,366,341,300)


total <- c(34,36,34,35)


incident_month_yr <- c("2017-2","2017-5","2018-2","2019-2")

df <- data.frame(incident_month_yr,pop.2017,pop.2018,pop.2019,pop.2020,total)

df['perc'] <- NA

对于 Incident_month_yr 包含 2017 年的行,我希望 perc 等于 total/pop.2017对于 Incident_month_yr 包含 2018 年的行,我希望 perc 等于 total/pop.2018对于 Incident_month_yr 包含 2019 年的行,我希望 perc 等于 total/pop.2019对于 Incident_month_yr 包含 2020 的行,我希望 perc 等于 total/pop.2020

我已经尝试过这个:

df$perc[grepl(2017,df$incident_month_yr)] <- df$total/df$pop.2017
df$perc[grepl(2018,df$incident_month_yr)] <- df$total/df$pop.2018
df$perc[grepl(2019,df$incident_month_yr)] <- df$total/df$pop.2019
df$perc[grepl(2020,df$incident_month_yr)] <- df$total/df$pop.2020

但是,它并没有像我想要的那样将计算应用于特定行。我怎样才能做到这一点?

最佳答案

您可以使用以下解决方案:

library(dplyr)
library(stringr)


df %>%
mutate(perc = ifelse(str_detect(incident_month_yr, "2017"), total/pop.2017,
ifelse(str_detect(incident_month_yr, "2018"), total/pop.2018,
total/pop.2019)))


incident_month_yr pop.2017 pop.2018 pop.2019 pop.2020 total perc
1 2017-2 434 334 477 474 34 0.07834101
2 2017-5 346 336 346 366 36 0.10404624
3 2018-2 345 325 145 341 34 0.10461538
4 2019-2 357 345 345 300 35 0.10144928

特别感谢亲爱的@akrun我们还可以用基础 R 中的 grepl 函数替换 str_detect 以使用更少的包,并使用 case_when 代替 ifelse作为非嵌套替代方案。

df %>%
mutate(perc = case_when(
grepl("2017", incident_month_yr) ~ total/pop.2017,
grepl("2018", incident_month_yr) ~ total/pop.2018,
TRUE ~ total/pop.2019
))

incident_month_yr pop.2017 pop.2018 pop.2019 pop.2020 total perc
1 2017-2 434 334 477 474 34 0.07834101
2 2017-5 346 336 346 366 36 0.10404624
3 2018-2 345 325 145 341 34 0.10461538
4 2019-2 357 345 345 300 35 0.10144928

关于r - R 中列的条件计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67510445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com