1

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

  • Welcome to SO. Please have a good look here and update you question: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – s_baldur Feb 06 '19 at 09:27
  • take a look at [this](https://stackoverflow.com/questions/45574212/quick-replace-of-na-an-error-or-warning/45574804#45574804) page! – patL Feb 06 '19 at 09:29

2 Answers2

1

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you it worked perfectly fine, but is it possible to add like a condition and say when value2 is equal to 0 then my result is 0 ? –  Feb 06 '19 at 09:45
  • @Arkning you could do replace the `Result` values for all `Value2 == 0` by doing `df$Result[df$Value2 == 0] <- 0` – Ronak Shah Feb 06 '19 at 09:51
  • I thought about that but I want to do that only for the NAs value at the start, because I might have a rows where I have Value2 = 0 but my result as already a value and I don't want to change it –  Feb 06 '19 at 09:54
  • Then i could do something like df$Result[df$Value2[inds] == 0] <- 0 ? –  Feb 06 '19 at 09:57
1

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))
Roman
  • 17,008
  • 3
  • 36
  • 49