Reputation:
So I have a data frame like this :
And I'd like that all and only the missing values that I have (NAs) are replaced by this formula : Value1 / Value2
I know how to do this with a loop, but when it comes to a large scale data frame it takes time so I was wondering if there is any function/tip to give me the expected result faster
Upvotes: 2
Views: 1017
Reputation: 17648
perfect for tidyverse
library(tidyverse)
d %>%
mutate(Result = ifelse(is.na(Result), Value1/Value2, Result)))
or
d %>%
mutate(Result = case_when(is.na(Result) & Value2 == 0 ~ Value2,
is.na(Result) ~ Value1/Value2,
TRUE ~ Result))
Upvotes: 1
Reputation: 389175
Not a direct function but something like this would work
#Get indices for NA non-zero values
inds1 <- is.na(df$Result) & df$Value2 != 0
#Get indices for NA zero values
inds2 <- is.na(df$Result) & df$Value2 == 0
#Replace them
df$Result[inds1] <- df$Value1[inds1]/df$Value2[inds1]
df$Result[inds2] <- 0
Upvotes: 1