R 合并多个数据帧的列,并基于列名覆盖值
我有以下数据:R 合并多个数据帧的列,并基于列名覆盖值,r,dataframe,merge,R,Dataframe,Merge,我有以下数据: x<-data.frame(A=c(1,NA),B=c(NA,NA),C=c(NA,1)) A B C 1 1 NA NA 2 NA NA 1 “我的数据”中的非NA值之间没有冲突。您可以尝试: library(dplyr) library(magrittr) full_join(x,y) %>% inner_join(y) %>% coalesce(full_join(x,y) %>%
x<-data.frame(A=c(1,NA),B=c(NA,NA),C=c(NA,1))
A B C
1 1 NA NA
2 NA NA 1
“我的数据”中的非NA值之间没有冲突。您可以尝试:
library(dplyr)
library(magrittr)
full_join(x,y) %>%
inner_join(y) %>%
coalesce(full_join(x,y) %>%
inner_join(x))
其中:
A B C D
1 1 NA NA NA
2 0 NA 1 0
您可以尝试:
library(dplyr)
library(magrittr)
full_join(x,y) %>%
inner_join(y) %>%
coalesce(full_join(x,y) %>%
inner_join(x))
其中:
A B C D
1 1 NA NA NA
2 0 NA 1 0
下面是一个基本的R方法,它应该是相当通用的
# fill in x NA values with values in y
x[] <- lapply(names(x), function(i) ifelse(is.na(x[,i]) & i %in% names(y), y[,i], x[,i]))
# add variables in y that are not in x and provide names to the variables
setNames(cbind(x, y[, !(names(y) %in% names(x))]), union(names(x), names(y)))
A B C D
1 1 NA NA NA
2 0 NA 1 0
#用y中的值填写x NA值
x[]这里有一个基本的R方法,应该是相当通用的
# fill in x NA values with values in y
x[] <- lapply(names(x), function(i) ifelse(is.na(x[,i]) & i %in% names(y), y[,i], x[,i]))
# add variables in y that are not in x and provide names to the variables
setNames(cbind(x, y[, !(names(y) %in% names(x))]), union(names(x), names(y)))
A B C D
1 1 NA NA NA
2 0 NA 1 0
#用y中的值填写x NA值
我不太明白你想做什么。优先考虑非NA值你这是什么意思?@Sotos我认为OP指的是NAs将被任何可用的非NA值取代的情况。我不太明白你想做什么。优先考虑非NA值这是什么意思?@Sotos我认为OP指的是NAs将被任何可用的非NA值取代的情况。