Assignment using logical sub-setting

How can I perform assignment using logical sub-setting? For example:

t1 <- tibble(x=1:5, y=6:10)
t1[1,1] <- NA_real_
t1[4,2] <- NA_real_

t2 <- tibble(x=11:15, y=16:20)

na_index <- is.na(t1)

t1[na_index] <- t2[na_index]

this last line gives me an error.

I don't think that tibbles support quite that operation. I.e. you can logically subset and supply a single value to go to all those positions, but you are wanting multiple values.

I think the dplyr way to fill NA values from one table with corresponding values from another in your example setup would be like this :

rows_update(rowid_to_column(t1),
            rowid_to_column(t2))  # |> select(-rowid)  ## optionally remove the rowid that was used.

It seems that rows_update does not work, but I found rows_patch in the same reference page, which does. Thank you @nirgrahamuk !

t1 <- tibble(x=1:5, y=6:10)
t1[1,1] <- NA_real_
t1[4,2] <- NA_real_

t2 <- tibble(x=11:15, y=16:20)

t3 <- rows_patch(rowid_to_column(t1), rowid_to_column(t2), by = "rowid") %>%
          select(!rowid)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.