user9459221
user9459221

Reputation:

Is there an R function to fill NA value of a column in a specific way?

So I have a data frame like this :

enter image description here

And I'd like that all and only the missing values that I have (NAs) are replaced by this formula : Value1 / Value2

enter image description here

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

Answers (2)

Roman
Roman

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

Ronak Shah
Ronak Shah

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

Related Questions