Reputation: 465
I'm new with R, and would like to do some basic things. I have three data frames with a column with the same name. In each data frame a different value is registered. (In my real data there are more values and off course NA)
Df1
Value
A 1
B NA
C NA
D NA
Df2
Value
A NA
B NA
C 2
D NA
Df3
Value
A NA
B NA
C NA
D 3
I want to combine the three data frames so I can complete the column. So I get this:
Df
Value
A 1
B NA
C 2
D 3
How can I do this in R?
Thank you.
Upvotes: 1
Views: 346
Reputation: 887901
One option in base R
is pmin/pmax
(assuming that there is only a single non-NA element at the same location). Place the objects in a list
(with mget
), and use pmin
with do.call
do.call(pmin, c(mget(paste0("Df", 1:3)), na.rm = TRUE))
# Value
#A 1
#B NA
#C 2
#D 3
Df1 <- structure(list(Value = c(1L, NA, NA, NA)), class = "data.frame", row.names = c("A",
"B", "C", "D"))
Df2 <- structure(list(Value = c(NA, NA, 2L, NA)), class = "data.frame", row.names = c("A",
"B", "C", "D"))
Df3 <- structure(list(Value = c(1L, NA, 2L, 3L)), class = "data.frame", row.names = c("A",
"B", "C", "D"))
Upvotes: 2
Reputation: 47350
Using dplyr::coalesce
:
library(dplyr)
Df <- data.frame(Value = coalesce(Df1$Value, Df2$Value,Df3$Value),
row.names = row.names(Df1))
Df
# Value
# A 1
# B NA
# C 2
# D 3
data
Df1 <- read.table(text="
Value
A 1
B NA
C NA
D NA",strin=F,h=T)
Df2 <- read.table(text="
Value
A NA
B NA
C 2
D NA",strin=F,h=T)
Df3 <- read.table(text="
Value
A NA
B NA
C NA
D 3",strin=F,h=T)
Upvotes: 3