在R语言中按Rows_to_repeat列值重复姓名生成目标数据框
解决方案:按指定重复次数匹配姓名与水果数据
问题说明
现有两个数据框:
Name_List:包含姓名及对应的重复次数Fruits_List:包含水果列表
需要生成Output数据框,将姓名按Rows_to_repeat列的数值重复对应次数后,与Fruits_List的每一行一一匹配。
示例数据
# 创建Name_List Name <- c("rohit","murali","partha") Rows_to_repeat <- c(6,3,1) Name_List <- data.frame(Name, Rows_to_repeat) # 创建Fruits_List Fruits <- c("Apple","Orange","Watermelon","Mango","Banana","Kiwi","Pomo","Dates","Muskmelon","Papaya") Fruits_List <- data.frame(Fruits) # 目标输出示例 Person_Got_Fruit <- c("rohit","rohit","rohit","rohit","rohit","rohit","murali","murali","murali","partha") Output <- data.frame(Fruits, Person_Got_Fruit)
方法1:基础R实现
用rep()函数根据重复次数生成姓名序列,直接与水果数据合并:
# 生成重复的姓名列 person_col <- rep(Name_List$Name, times = Name_List$Rows_to_repeat) # 合并得到结果 result <- cbind(Fruits_List, Person_Got_Fruit = person_col)
方法2:tidyverse实现
借助dplyr和tidyr的uncount()函数展开姓名数据,再与水果列表合并:
library(tidyverse) # 按重复次数展开姓名行 expanded_names <- Name_List %>% uncount(Rows_to_repeat) %>% rename(Person_Got_Fruit = Name) # 合并数据 result <- bind_cols(Fruits_List, expanded_names)
结果验证
两种方法生成的result与示例中的Output完全一致:
> all.equal(result, Output) [1] TRUE
内容的提问来源于stack exchange,提问作者ParthaSarathi
相关产品推荐
相关产品推荐

