missing variable

Hi Guys,

Apologies in advance if this is too basic for this community.

I have a dataframe like the one attached here. And I want to tell R to do this: B1 + B2 /2 for every missing variable in column B4, and then create (write this) a new column A1.
I have unsuccessfully attempted to resolve this using:
mydata$A1 = ifelse(mydata$B4 %in% c("NA") ,(mydata$B1 + mydata$B2) /2

Any advice will be appreciated.


1 Like

A Tidyverse approach is below. Are these results like what you need?


my_dat <- tibble(B1 = 1:2, B2 = 3:4, B4 = c(1, NA))

my_dat %>%
  mutate(A1 = case_when(is.na(B4) ~ (B1 + B2) / 2))
#> # A tibble: 2 x 4
#>      B1    B2    B4    A1
#>   <int> <int> <dbl> <dbl>
#> 1     1     3     1     NA
#> 2     2     4    NA     3

Created on 2021-06-21 by the reprex package (v2.0.0)

1 Like

Using EeethB's data set from above, I'd do the following:

mydata <- tibble(B1 = 1:2, B2 = 3:4, B4 = c(1, NA))

mydata$A1 <- ifelse(is.na(mydata$B4) ,(mydata$B1 + mydata$B2) /2,"")

I think you need to specify the last argument of ifelse, as in you need to decide what goes into A1 if the observation in B4 is not NA. Obviously EeethB's elegant solution works well too


Excellent, exactly what I need.
Thank you so much.

1 Like

Awesome. Thank you so much.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.