在数据框中的不同变量之间迭代 mutate 函数

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

我需要一个变异和迭代函数,它将组合 6 个变量(第 1 到 6 个、第 7 到 12 个……)并使用下面的示例数据集创建 1 个新的组合变量:

包含 75 个变量的示例数据框(测试 75)

test75 <- data.frame(matrix(sample(0:1, 75 * 6, replace = TRUE), ncol = 75))
names(test75) <- paste0("Q", 1:75)
r dplyr mutate
1个回答
0
投票

#我之前尝试过,但没有成功,但我找到了一个解决方案,我在下面发布了针对相同数据集的解决方案。

library(dplyr)
library(tidyverse)
library(janitor) 

# Sample dataset with a data frame with 75 variables (test 75)
test75 <- data.frame(matrix(sample(0:1, 75 * 6, replace = TRUE), ncol = 75))
names(test75) <- paste0("Q", 1:75)
view(test75)

# 1. Define the transformation function
apply_transformations <- function(df, start) {
  if (start + 5 <= ncol(df)) {  # Ensure there is group of 6 to process
    vars_in_group <- names(df)[start:(start+5)]
    combined_name <- paste0("Q", start, "Combined")
    
    df <- df %>%
      mutate(!!combined_name := case_when(
        !!sym(vars_in_group[1]) == 1 ~ 5,
        !!sym(vars_in_group[2]) == 1 ~ 4,
        !!sym(vars_in_group[3]) == 1 ~ 3,
        !!sym(vars_in_group[4]) == 1 ~ 2,
        !!sym(vars_in_group[5]) == 1 ~ 1,
        !!sym(vars_in_group[6]) == 1 ~ 99,
        TRUE ~ 0
      ))
  }
  return(df)
}

# 2. Calculate appropriate indices to start each group
indices <- seq(1, ncol(test75) - 6, by = 8)

# 3. Apply the function to each group starting index
for (index in indices) {
  test75 <- apply_transformations(test75, index)
}

# Print the resulting data frame to see some of the combined variables
print(head(test75))
view(test75)
© www.soinside.com 2019 - 2024. All rights reserved.