如何根据两文件的匹配条件从另一文件导入信息?
问题与解决方案
输入数据
file_1
ID L_meat a_meat b_meat L_fat a_fat b_fat 1 21 21 21 22 22 22 2 23 23 23 24 24 24
file_2
Sample L a b 21 37.34 16.53 14.72 22 79.92 2.90 10.70 23 37.49 15.57 14.16 24 71.03 2.51 10.44
期望输出
ID L_meat a_meat b_meat L_fat a_fat b_fat 1 37.34 16.53 14.72 79.92 2.90 10.70 2 37.49 15.57 14.16 71.03 2.51 10.44
原代码问题
你尝试的代码存在三个问题:
- 列名拼写错误:
file_2$Amostra应为file_2$Sample; - 向量长度不匹配:file_1有2行,file_2有4行,直接用
==会触发R的循环回收机制,导致匹配逻辑混乱; - 仅处理了
L_meat一列,未覆盖其他需要替换的列。
可行解决方案
方法1:基础R实现
利用match()函数精准匹配对应值,批量替换列:
# 定义需要处理的列组 meat_cols <- c("L_meat", "a_meat", "b_meat") fat_cols <- c("L_fat", "a_fat", "b_fat") file_2_value_cols <- c("L", "a", "b") # 替换meat相关列:根据L_meat匹配file_2的Sample,提取对应L/a/b值 meat_match_pos <- match(file_1$L_meat, file_2$Sample) file_1[meat_cols] <- file_2[meat_match_pos, file_2_value_cols] # 替换fat相关列:根据L_fat匹配file_2的Sample,提取对应L/a/b值 fat_match_pos <- match(file_1$L_fat, file_2$Sample) file_1[fat_cols] <- file_2[fat_match_pos, file_2_value_cols]
方法2:tidyverse(dplyr)实现
如果习惯使用tidyverse语法,可通过连接操作完成替换:
library(dplyr) library(stringr) # 重命名file_2的列,分别适配meat和fat的替换需求 file_2_meat <- file_2 %>% rename(L_meat = L, a_meat = a, b_meat = b) file_2_fat <- file_2 %>% rename(L_fat = L, a_fat = a, b_fat = b) # 依次匹配替换meat和fat列 file_1 <- file_1 %>% left_join(file_2_meat, by = c("L_meat" = "Sample")) %>% select(-ends_with(".x")) %>% rename_with(~str_remove(., ".y")) %>% left_join(file_2_fat, by = c("L_fat" = "Sample")) %>% select(-ends_with(".x")) %>% rename_with(~str_remove(., ".y"))
内容的提问来源于stack exchange,提问作者Curious G.
相关产品推荐
相关产品推荐

