You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中按指定规则合并两组各含5个变量的序列数据的方法

R中按规则合并两组二值序列的实现方法

核心逻辑

你给出的映射规则可以直接转化为算术公式,无需复杂的条件判断:
合并后取值 = 序列1对应值 * 2 + 序列2对应值 + 1
验证完全符合需求:

  • 0*2 + 0 + 1 = 1(对应0+0场景)
  • 0*2 + 1 + 1 = 2(对应0+1场景)
  • 1*2 + 0 + 1 = 3(对应1+0场景)
  • 1*2 + 1 + 1 = 4(对应1+1场景)

实现代码

方法1:基础R实现(兼容性最好)

# 生成示例数据
set.seed(145)
mm <- matrix(0, 5, 10)
df <- data.frame(apply(mm, c(1,2), function(x) sample(c(0,1),1)))
colnames(df) <- c("s1_1", "s1_2", "s1_3", "s1_4", "s1_5", "s2_1", "s2_2", "s2_3", "s2_4", "s2_5")

# 合并计算
n_var <- 5 # 每组变量的数量
merged_df <- data.frame(matrix(NA, nrow = nrow(df), ncol = n_var))
colnames(merged_df) <- paste0("merged_", 1:n_var)

for (i in 1:n_var) {
  s1_col <- paste0("s1_", i)
  s2_col <- paste0("s2_", i)
  merged_df[[i]] <- df[[s1_col]] * 2 + df[[s2_col]] + 1
}

# 合并结果与原数据
df_full <- cbind(df, merged_df)

方法2:矩阵运算(适合大数据量场景,效率最高)

s1_mat <- as.matrix(df[, paste0("s1_", 1:5)])
s2_mat <- as.matrix(df[, paste0("s2_", 1:5)])
merged_mat <- s1_mat * 2 + s2_mat + 1
colnames(merged_mat) <- paste0("merged_", 1:5)
df_full <- cbind(df, merged_mat)

方法3:tidyverse语法实现

library(dplyr)
library(stringr)

df_full <- df %>%
  mutate(across(starts_with("s1_"), 
                ~ .x * 2 + get(paste0("s2_", str_extract(cur_column(), "\\d+$"))) + 1,
                .names = "merged_{str_extract(.col, '\\d+$')}"))

验证示例:示例数据第一行s1_1=1、s2_1=0,运行代码后merged_1第一行取值为3,完全符合规则要求。

内容的提问来源于stack exchange,提问作者cliu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:09