如何将R语言数据集重塑为Source与Target两列结构
数据集重塑解决方案
需求说明
将给定的R数据集转换为仅包含Source和Target的两列结构:
- Source:每个
Comments分组中,Prompt等于"who"对应的Response值 - Target:同一
Comments分组中,Prompt等于"was"对应的Prompt.Label值
原始数据集
data <- structure(list(Response = c("Friend", "1", "1", "Family", "1", "1", "other", "1", "other", "1", "Friend", "1", "Family", "1" ), Prompt = c("who", "was", "was", "who", "was", "was", "who", "was", "who", "was", "who", "was", "who", "was"), Prompt.Label = c("si3", "si4_en", "si4_nag", "si3", "si4_nag", "si4_en", "si3", "si4_sp", "si3", "si4_en", "si3", "si4_en", "si3", "si4_en"), Comments = c("3_a", "3_a", "3_a", "3_b", "3_b", "3_b", "4_a", "4_a", "4_b", "4_b", "5_a", "5_a", "5_b", "5_b")), class = "data.frame", row.names = c(NA, -14L))
解决方案代码
使用dplyr包拆分并连接数据集:
library(dplyr) # 提取每个分组的Source值 source_data <- data %>% filter(Prompt == "who") %>% select(Source = Response, Comments) # 提取每个分组的Target值 target_data <- data %>% filter(Prompt == "was") %>% select(Target = Prompt.Label, Comments) # 按Comments分组关联,得到最终结果 final_data <- source_data %>% inner_join(target_data, by = "Comments") %>% select(Source, Target) # 查看结果 print(final_data)
运行结果
Source Target 1 Friend si4_en 2 Friend si4_nag 3 Family si4_nag 4 Family si4_en 5 other si4_sp 6 other si4_en 7 Friend si4_en 8 Family si4_en
内容的提问来源于stack exchange,提问作者Ali Roghani
相关产品推荐
相关产品推荐

