gpt4 book ai didi

r - 如何在 r 中的 if else 流控制中测试多个条件

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

这似乎是一个非常简单的流控制结构疑问,但是我很难在 R 中找到正确的语法,我已经尝试了很多没有成功。我一定错过了一些非常明显的东西。

我想在一个包含巴西州代码的列表中循环,并返回它所在的区域。我的目标是操作一个更大的数据集,而不是一个列表,但这里是一个使用列表的 MWE:

a <- c("RO", "AC", "AM" ,"RR", "PA", "AP", "TO", "MA", "PI", "CE", "RN", "PB", "PE", "AL", "SE", "BA", "MG", "ES", "RJ", "SP")

setregion <- function(uf) {
pb = txtProgressBar(min = 0, max = length(uf), initial = 0)
region_out<-list()
for (i in length(uf)) {
if (uf %in% c("RO" ,"AC" ,"AM" ,"RR", "PA" , "AP" , "TO")) {
region_out <- append(region_out,"North")
} else if ( uf %in% c("MA","PI","CE","RN","PB","PE","AL","SE","BA")) {
region_out <-append(region_out,"Northeast")
} else if ( uf %in% c("MG","ES","RJ","SP")){
region_out <- append(region_out,"Southeast")
} else if ( uf %in% c("PR", "SC", "RS")){
region_out <- append(region_out,"South")
} else if ( uf %in% c("MS","MT","GO", "DF")){
region_out <-append(region_out,"Midwest")
}
setTxtProgressBar(pb,i)
}
return(region_out)
}

setregion(a)

在运行上面的代码时,似乎 if 循环也打破了 for 循环,它只返回“North”,这是对列表中第一个项目的响应。

我希望列表看起来像:
"North", "North", "North" ,"North", "North", "North","North", "Northeast", "Northeast",...
  • 我错过了什么?
  • 最佳答案

    普通 if-else 的问题在于它没有向量化。您需要一种矢量化方法,例如 ifelse 函数。但是,在您的情况下,由于您有很多条件,case_when 库中的 dplyr 函数可能更有意义:

    library(dplyr)

    setregion <- function(uf) {
    region_out <- case_when(
    uf %in% c("RO","AC","AM","RR","PA","AP","TO") ~ "North",
    uf %in% c("MA","PI","CE","RN","PB","PE","AL","SE","BA") ~ "Northeast",
    uf %in% c("MG","ES","RJ","SP") ~ "Southeast",
    uf %in% c("PR", "SC", "RS") ~ "South",
    uf %in% c("MS","MT","GO", "DF") ~ "Midwest"
    )
    return(region_out)
    }

    关于r - 如何在 r 中的 if else 流控制中测试多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54767257/

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