1
votes

I'm sure there is a very easy way to accomplish this task, but I cannot seem to figure it out. I have two data frames which have the exact same data but from two separate locations.

df1 <- data.frame(a=c(1,2,3,NA),b=c(1,5,4,6))
df2 <- data.frame(a=c(3,4,5,6),b=c(7,8,9,NA))

My desired output is two have a new version of df1 and df2 which are the exact same but the bottom row only contains NA values. I.e. if there is an NA value in one data frame, I need that replicated on the corresponding cell in the other data frame...

df1[4,2] <- NA
df2[4,1] <- NA

I have seen very similar questions addressing the problem from the opposite perspective (e.g. Filling missing values in a data.frame from another data.frame) but I can't figure how to apply this to my own data. Thank you in advance.

2

2 Answers

3
votes

We can create an index based on the occurrence of NA in either of the two datasets and multiply

i1 <- NA^(is.na(df1)| is.na(df2))
df1 <- df1 * i1
df2 <- df2 * i1
3
votes

Here are some possibilities. (1) seems the cleanest and clearest in intent. (3) works but seems unnecessarily complex in terms of sorting out side effects.

1) replace Try replace.

df1new <- replace(df1, is.na(df2), NA)
df2new <- replace(df2, is.na(df1), NA)

This would continue to work if df1new and df2new were replaced with df1 and df2 although it adds complexity. In that case it might be better to assign df1 and df2 (i.e. df1 <- df1new; df2 <-df2new) afterwards to avoid complexity.

2) indexing It could alternately be written like this:

df1new <- df1
df1new[is.na(df2)] <- NA

df2new <- df2
df2new[is.na(df1)] <- NA

3) destructive indexing Not sure that this one is a good idea but it works here:

df1[is.na(df2)] <- df2[is.na(df1)] <- NA