在R中基于列值新增行:将理想值列转为Product列标注为ideal的行
R数据预处理:Ideal前缀列转ideal产品行解决方案
我们可以通过tidyverse系列包快速实现需求,核心逻辑是先提取每个消费者的唯一理想值,整理为符合原数据结构的新行后与原数据集合并:
方法1:tidyverse 实现(推荐)
步骤1:加载依赖包
library(tidyverse)
步骤2:数据转换代码
df_result <- df %>% # 提取每个消费者的唯一理想值(同个消费者的Ideal列值完全一致,去重减少冗余计算) distinct(Consumer, .keep_all = T) %>% select(Consumer, starts_with("Ideal_")) %>% # 去除列名的Ideal_前缀,和原数据的评分列对齐 rename_with(~str_remove(.x, "Ideal_"), starts_with("Ideal_")) %>% # 新增Product列标注为ideal mutate(Product = "ideal") %>% # 和删除了Ideal列的原数据合并 bind_rows(df %>% select(-starts_with("Ideal_"))) %>% # 按消费者编号排序,方便核对结果 arrange(Consumer)
方法2:Base R 实现(无第三方依赖)
# 提取每个消费者的唯一理想值 ideal_rows <- unique(df[, c("Consumer", "Ideal_Firm", "Ideal_Juicy", "Ideal_Sweet")]) # 重命名列,移除Ideal_前缀 colnames(ideal_rows) <- gsub("Ideal_", "", colnames(ideal_rows)) # 新增Product列标注为ideal ideal_rows$Product <- "ideal" # 合并数据,移除原数据的Ideal开头列 df_result <- rbind(df[, !grepl("Ideal_", colnames(df))], ideal_rows) # 按消费者编号排序 df_result <- df_result[order(df_result$Consumer), ]
输出说明
转换后的数据会保留原有的所有产品行,同时为每个消费者新增1行Product为"ideal"的记录,对应Firm、Juicy、Sweet值为原Ideal_*列的取值,原Ideal_开头的列会被移除。
内容的提问来源于stack exchange,提问作者Inshal Khan
相关产品推荐
相关产品推荐

