Why does it return NA value when I create a new variable using mutate() function

Viewed 131

I compute the following code:

df <- df %>% 
  mutate(PPE = (prop)+(equip))
# create new variable depending on this
df <- df %>% 
  mutate(dependent = (PPE - lag(PPE))/lag(assets))

and when I look at the data, PPE returns NA because equip has a NA value. However, say prop = 1 and equip = NA, I would like PPE to return 1 (and not NA). How can I change this? There is an example below of what I would want (where the first observation has to return NA for the dependent variable as I am using lag):

prop    equip    assets   PPE   dependent
  1       NA        2      1        NA 
​  1       NA        1      1        0.5
​  NA       4        2      4        3 
​  3       3         1      6        1 
​  8       NA        2      8        2  

Thanks in advance for any help on this!

1 Answers

The reason is because lag by default fills with default = NA as the first element.. If we need to get 1, then we can replace the NA with 1 or specify the default` with a different value

df %>% 
     mutate(dependent = replace_na((PPE - lag(PPE))/lag(assets), 1))

If the error is from prop + equip, it is because one of the column have NA values and adding an element or multiplying or other arithmetic operations on NA returns NA. To avoid that, we can use rowSums with na.rm = TRUE

 df$PPE <- rowSums(df[c("prop", "equip")], na.rm = TRUE)
Related