I am interested in replacing all NAs in a row with a reference value from that same row. The following code works, but too slowly for my actual use case:
df = data.frame(ref = c(1,3,4,2,5), var1 = c(NA,3,4,2,1), var2 = c(1,3,NA,5,5))
for (i in 1:nrow(df)) {
ref_value = as.character(df$ref[i])
df[i,] = df[i,] %>% mutate_all(replace_na, replace = ref_value) }
I tried to speed up the process with the following modification and got the error below.
df = data.frame(ref = c(1,3,4,2,5), var1 = c(NA,3,4,2,1), var2 = c(1,3,NA,5,5))
df %>% rowwise() %>% mutate_all(replace_na, replace = ref)
error:
Error: Problem with mutate() input ref.
x Replacement for data is length 2, not length 1
ℹ Input ref is (function (data, replace, ...) ....
ℹ The error occured in row 1.
Any suggestions?