Daniel Wilkerson
Daniel Wilkerson

Reputation: 11

Merging three vectors with NaN's

I have three vectors that look something like this:

x = c(NaN, 15, 16, 14, 14, NaN)
y = c(NaN, NaN, NaN, NaN, NaN, 11)
z = c(17, NaN, NaN, NaN, NaN, 12)

I need to merge them into one vector. I need these three to mesh together smoothly, and where there are overlapping values (as seen in y and z), priority should be given to the value from z. The end result should look like so:

xyz = c(17, 15, 16, 14, 14, 12)

I've looked into using rowSums to handle the na's, but this doesn't work in cases where there are multiple values on the same index. I'm trying to avoid for loops if possible.

Pretty sure I could do this by iterating through the vectors but I'm working with a fairly large data set.

Upvotes: 1

Views: 85

Answers (2)

Dan
Dan

Reputation: 12074

This seems to work. NB It relies on z being the last column of the data frame, then flips it so that it's first (i.e., rev).

df <- data.frame(x = c(NaN, 15, 16, 14, 14, NaN),
            y = c(NaN, NaN, NaN, NaN, NaN, 11),
            z = c(17, NaN, NaN, NaN, NaN, 12))

do.call(dplyr::coalesce, rev(df))


You can also use zoo package:

df <- rbind(x, y, z)

#it replaces last row with latest non-NA value therefore z always has priority:
xyz <- zoo::na.locf(df)['z',]

#[1] 17 15 16 14 14 12

Data:

x <- c(NaN, 15, 16, 14, 14, NaN)
y <- c(NaN, NaN, NaN, NaN, NaN, 11)
z <- c(17, NaN, NaN, NaN, NaN, 12)

Upvotes: 2

BENY
BENY

Reputation: 323226

Or you can using base R function na.omit

x = c(NaN, 15, 16, 14, 14, NaN)
y = c(NaN, NaN, NaN, NaN, NaN, 11)
z = c(17, NaN, NaN, NaN, NaN, 12)
dt=data.frame(z=z,x=x,y=y)
unlist(lapply(apply(dt,1,na.omit), `[[`, 1))

[1] 17 15 16 14 14 12

Upvotes: 0

Related Questions