Ruben Basantes
Ruben Basantes

Reputation: 11

Replace specific rows with NA values from another data.frame

Y have 2 dataframes with the same number of columns and rows. I need replace NA values in specific rows of dfA with values in same rows from dfB. For example:

dfA

X Y Z
NA NA NA
74 42 18
NA NA NA
NA NA NA

dfB

X Y Z
250 456 258
145 745 251
236 257 159
753 852 456

I tried

dfA[c(1,3,4),] <-replace(dfA[c(1,3,4),], is.na(dfA[c(1,3,4),]), dfA[c(1,3,4),])

the expected result should be
dfA

X Y Z
250 456 258
74 42 18
236 257 159
753 852 456

but I get

dfA

X Y Z
c(250,456,258) c(250,456,258) c(250,456,258)
74 42 18
c(236,257,159) c(236,257,159) c(236,257,159)
c(753,852,456) c(753,852,456) c(753,852,456)

Thanks for your valuable help!

Upvotes: 1

Views: 25

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102529

If you have specified the rows for the replacement, you can try

> dfA[c(1, 3, 4), ] <- dfB[c(1, 3, 4), ]

> dfA
    X   Y   Z
1 250 456 258
2  74  42  18
3 236 257 159
4 753 852 456

If you want to replace all NA by values from dfB, with base R, you can try

> list2DF(Map(\(a, b) ifelse(is.na(a), b, a), dfA, dfB))
    X   Y   Z
1 250 456 258
2  74  42  18
3 236 257 159
4 753 852 456

or

> replace(dfA, is.na(dfA), dfB[is.na(dfA)])
    X   Y   Z
1 250 456 258
2  74  42  18
3 236 257 159
4 753 852 456

data

> dput(dfA)
structure(list(X = c(NA, 74L, NA, NA), Y = c(NA, 42L, NA, NA),
    Z = c(NA, 18L, NA, NA)), class = "data.frame", row.names = c(NA,
-4L))

> dput(dfB)
structure(list(X = c(250L, 145L, 236L, 753L), Y = c(456L, 745L,
257L, 852L), Z = c(258L, 251L, 159L, 456L)), class = "data.frame", row.names = c(NA,
-4L))

Upvotes: 1

Related Questions