我想融合3个数据帧(AA、AB和BB),它们包含完全相同的维度,并且永远不会在同一个坐标中包含一个数字(如果其中一个包含一个数字,其他的将包含一个NA。也可以是一个特定的坐标包含所有数据帧的NA )。这是我的意见:
AA <- 'pr_id sample1 sample2 sample3
AX-1 NA 120 130
AX-2 NA NA NA
AX-3 NA NA NA'
AA <- read.table(text=AA, header=T)
AB <- 'pr_id sample1 sample2 sample3
AX-1 100 NA NA
AX-2 NA 180 NA
AX-3 NA 120 NA'
AB <- read.table(text=AB, header=T)
BB <- 'pr_id sample1 sample2 sample3
AX-1 NA NA NA
AX-2 150 NA NA
AX-3 160 NA NA'
BB <- read.table(text=BB, header=T) 我的预期产出:
Fus <- 'pr_id sample1 sample2 sample3
AX-1 100 120 130
AX-2 150 180 NA
AX-3 160 120 NA'
Fus <- read.table(text=Fus, header=T)做这种融合的想法吗?
发布于 2016-01-27 13:04:31
这里有一个可能的解决方案,给你一个矩阵
L <- lapply(list(AA, AB, BB), function(x) { row.names(x) <- x[[1]]; as.matrix(x[-1])})
Reduce(function(x, y) ifelse(is.na(x), y, x), L)如果你想要一个数据文件:
L <- lapply(list(AA, AB, BB), function(x) { row.names(x) <- x[[1]]; as.matrix(x[-1])})
X <- Reduce(function(x, y) ifelse(is.na(x), y, x), L)
as.data.frame(X) # Fus <- as.data.frame(X)您也可以在一个循环中这样做:
L <- lapply(list(AA, AB, BB), function(x) { row.names(x) <- x[[1]]; as.matrix(x[-1])})
X <- L[[1]]
for (i in 2:length(L)) X <- ifelse(is.na(X), L[[i]], X)
X或
L <- lapply(list(AA, AB, BB), function(x) { row.names(x) <- x[[1]]; as.matrix(x[-1])})
X <- L[[1]]
for (i in 2:length(L)) X[is.na(X)] <- L[[i]][is.na(X)]
X发布于 2016-01-27 13:21:55
还可以定义一个新运算符来执行加法。
"%++%" <- Vectorize(function(x, y) {
if(is.na(x) && is.na(y)){
return(NA)
} else {
return(sum(c(x, y), na.rm=T))
}
})
cbind(AA[, 1, drop=F], matrix(as.matrix(AA[, 2:4]) %++%
as.matrix(AB[, 2:4]) %++%
as.matrix(BB[, 2:4]), ncol=3))
# pr_id 1 2 3
# 1 AX-1 100 120 130
# 2 AX-2 150 180 NA
# 3 AX-3 160 120 NAhttps://stackoverflow.com/questions/35036307
复制相似问题