根据字符串匹配动态mutate case_when

问题描述 投票:0回答:1

我有一个向量,它存储定性变量的所有可能的合并组合。
该向量具有以下结构:

Config = c("4 With 1 + 6 With 2 + 8 With 3","4 With 1 With 2 + 6 With 8")

这意味着具有 Config 第一个值的变量应该有 3 种模式:值 4 与 1 、值 6 与 2 、值 8 与 3

我想以动态方式为这次合并的每个元素分配一个动态值,例如:

mtcars %>% mutate(Merging=case_when(carb %in% c(4,1)~"Group 1", carb %in% c(6,2)~"Group 2",carb %in% c(8,3) ~"Group 3"))

我的主要困难是配置的每个元素的组数不相同:对于一种配置,可能是 3 组,对于另一种配置可能是 4 组,等等。

我已经尝试过使用字符串匹配,但这种可能性仅适用于仅包含单词“With”的 1 个组:

mutate(Merging= case_when(
      !!sym(VAR) %in% c(unlist(str_split(Config, " With "))) ~ "Group 1",
      TRUE ~ !!sym(VAR)
    ))

是否有一种方法可以为向量的每个元素动态执行此操作并在每次迭代时创建专用变量?

非常感谢

r dplyr tidyverse stringr tidytable
1个回答
0
投票

可以吗

library(dplyr)
library(stringr)
library(purrr)
library(rlang)

# Sample data
Config <- c("4 With 1 + 6 With 2 + 8 With 3", "4 With 1 With 2 + 6 With 8")
mtcars <- data.frame(carb = c(4, 1, 2, 6, 8, 3)) # Sample data

# Function to create dynamic conditions
create_conditions <- function(config) {
  pairs <- str_split(config, "\\s*\\+\\s*")[[1]]
  
  conditions <- map2(pairs, 1:length(pairs), function(pair, group_num) {
    values <- as.numeric(str_extract_all(pair, "\\d+")[[1]])
    group_name <- paste("Group", group_num)
    condition <- expr(carb %in% c(!!!values) ~ !!group_name)
    return(condition)
  })
  
  return(conditions)
}

# Create a list of conditions for each element of Config
conditions_list <- map(Config, create_conditions)

# Create a dynamic column using case_when
mtcars <- mtcars %>%
  mutate(Merging = case_when(!!!set_names(unlist(conditions_list), NULL)))

# View the result
print(mtcars)
© www.soinside.com 2019 - 2024. All rights reserved.