r - Fusing dfs with equal dimmensions -
i fuse 3 data frames (aa
, ab
, bb
) contain same dimensions , never contain number in same coordinate (if 1 contain number others contain na
. can true specific coordinate contain na
data frames). input:
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)
my expected output:
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)
some idea perform fusion?
here possible solution giving matrix
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)
if want dataframe:
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)
you can in loop:
l <- lapply(list(aa, ab, bb), function(x) { row.names(x) <- x[[1]]; as.matrix(x[-1])}) x <- l[[1]] (i in 2:length(l)) x <- ifelse(is.na(x), l[[i]], x) x
or
l <- lapply(list(aa, ab, bb), function(x) { row.names(x) <- x[[1]]; as.matrix(x[-1])}) x <- l[[1]] (i in 2:length(l)) x[is.na(x)] <- l[[i]][is.na(x)] x
Comments
Post a Comment