gpt4 book ai didi

r - ifelse 语句超出限制

转载 作者:行者123 更新时间:2023-12-01 16:43:43 26 4
gpt4 key购买 nike

问题:我编写了一段包含超过 100 个 ifelse 语句的巨大代码,却发现 ifelse 语句的数量有限制:超过 50 条会抛出异常错误。无论如何,我知道有一种更有效的方法来完成我想做的事情。

目标:尝试编写一个函数将字符串的许多变体(参见下面的示例)重新编码为清晰的类别(例如下面)。我使用 str_detect 给出 T/F,然后根据响应更改为正确的类别。如何在没有超过 100 个 ifelse 语句的情况下做到这一点(我有更多类别)。

示例:

mydf <- data_frame(answer = sample(1:5, 10, replace = T),
location = c("at home", "home", "in a home",
"school", "my school", "School", "Work", "work",
"working", "work usually"))

loc_function <- function(x) {
home <- "home"
school <- "school"
work <- "work"
ifelse(str_detect(x, regex(home, ignore_case = T)), "At Home",
ifelse(str_detect(x, regex(school, ignore_case = T)), "At
School",
ifelse(str_detect(x, regex(work, ignore_case = T)), "At
Work", x)))
}

### Using function to clean up messy strings (and recode first column too) into clean categories
mycleandf <- mydf %>%
as_data_frame() %>%
mutate(answer = ifelse(answer >= 2, 1, 0)) %>%
mutate(location = loc_function(location)) %>%
select(answer, location)

mycleandf

# A tibble: 10 x 2
answer location
<dbl> <chr>
1 1 At Home
2 1 At Home
3 1 At Home
4 1 At School
5 1 At School
6 1 At School
7 1 At Work
8 0 At Work
9 1 At Work
10 0 At Work

最佳答案

您可以将模式放入命名向量中,(请注意 Other = "",当您的模式均不与字符串匹配时,这是一个后备方案):

patterns <- c("At Home" = "home", "At School" = "school", "At Work" = "work", "Other" = "")

然后循环遍历模式并检查字符串是否包含模式:

match <- sapply(patterns, grepl, mydf$location, ignore.case = T)

最后建立新列,检查匹配模式的名称,即您要替换的模式,如果没有匹配的内容,则返回到“其他”:

mydf$clean_loc <- colnames(match)[max.col(match, ties.method = "first")]
mydf

# A tibble: 10 x 3
# answer location clean_loc
# <int> <chr> <chr>
# 1 3 at home At Home
# 2 3 home At Home
# 3 3 in a home At Home
# 4 3 school At School
# 5 2 my school At School
# 6 4 School At School
# 7 5 Work At Work
# 8 1 work At Work
# 9 2 working At Work
#10 1 work usually At Work

关于r - ifelse 语句超出限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45314395/

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