I am wanting to create a function in R, that would output flag variables that are derived from the original variables in the data frame, and then ideally for every variable in the data frame.
I want to create a new variable for each variable in the data frame, and the value would be equal to 1 if the original variable value is NA, or it would be equal to 0 if not NA.
I also want to call the new variable the same thing as the original variable, except with the prefix of "M_" before it.
Here is an example:
INDEX HEIGHT LENGTH
1 70 55
2 60 NA
3 NA 35
4 NA NA
I would want the output to look like this:
INDEX HEIGHT M_HEIGHT LENGTH M_LENGTH
1 70 0 55 0
2 60 0 NA 1
3 NA 1 35 0
4 NA 1 NA 1
I am currently doing this for each variable individually, but I want to speed things up and not have to repeat the same thing over and over.
df$M_HEIGHT <- ifelse(is.na(HEIGHT),1,0)
The "[<-" function can create (assign) new columns by name:
> dat[ , paste0( "M_",names(dat)[-1])] <-
lapply(dat[-1], function(x) as.numeric(is.na(x)) )
> dat
INDEX HEIGHT LENGTH M_HEIGHT M_LENGTH
1 1 70 55 0 0
2 2 60 NA 0 1
3 3 NA 35 1 0
4 4 NA NA 1 1
Since you wanted to assign the expected 0/1 values for the is.na logical test there was no need for an ifelse. You could have used ifelse if there were a more complex test or value range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With