在R中使用full_join函数报错及缺失值补0的解决求助
R数据拼接问题解决
1. 解决full_join报错问题
报错原因是你误将base R中merge()函数的all=TRUE参数用到了dplyr的full_join()里——full_join()本身就是全连接逻辑,不需要额外传递该参数,多余参数触发了报错。
把出错的代码行:
ESL <- full_join(ESL, ESL_SMBPN, all = TRUE, by = "Institution");
修改为:
ESL <- full_join(ESL, ESL_SMBPN, by = "Institution");
2. 拼接后缺失值替换为0
拼接完成后,用dplyr的across()函数批量将数值型列中的缺失值(NA)替换为0,不会影响非数值类型的列:
# 处理table1的缺失值 table1 <- table1 %>% mutate(across(where(is.numeric), ~replace(., is.na(.), 0))) # 处理table1_Revised的缺失值 table1_Revised <- table1_Revised %>% mutate(across(where(is.numeric), ~replace(., is.na(.), 0)))
完整修正后的代码
library(dplyr) # 执行全连接(移除错误的all=TRUE参数) ESL <- full_join(ES_Liquidity, ES_Liquidity_prev, by = "Institution") ESL_SMBPN <- full_join(ES_Liquidity_SMBPN, ES_Liquidity_SMBPN_prev, by = "Institution") ESL <- full_join(ESL, ESL_SMBPN, by = "Institution") table1 <- full_join(SC, ESL, by = "Institution") table1_Revised <- full_join(SC_Revised, ESL, by = "Institution") # 替换数值列的缺失值为0 table1 <- table1 %>% mutate(across(where(is.numeric), ~replace(., is.na(.), 0))) table1_Revised <- table1_Revised %>% mutate(across(where(is.numeric), ~replace(., is.na(.), 0)))
内容的提问来源于stack exchange,提问作者aaliad
相关产品推荐
相关产品推荐

