0
votes

I have 115 variables in my data frame, and I need to create a dummy variable for each variable that has negative value or values of 999. The dummy indicator will take a value of 1 if the original x value is <0 or 999 and 0 otherwise. For example for the following data frame

at<-c(1,-9,-1,999)
Bc<-c(1,-2,999,0)
df<-data.frame(at,Bc)

I want to have an output dataframe with the following format:

at        Bc    I.at    I.Bc
 1         1      0       0
-9        -2      1       1
-1        999     1       1
999        0      1       0
3
What have you tried? There are many ways to add variables to a data frame. Base R: df$Iat <- ifelse( df$at < 0 | df$at == 999, 1,0 ) - Ryan Morton
well, your code is what i knew but since i have 115 variables in my data set and i want to create this indicator for each one of them, thats where i got stuck and i was wondering if i could do this for all the variables at once and not separately for each one of them. - sahboor
dplyr::mutate_all() - Ryan Morton

3 Answers

1
votes

You can use a base R solution like this:

transform(df,I=ifelse(df<0|df==999,1,0))
   at  Bc I.at I.Bc
1   1   1    0    0
2  -9  -2    1    1
3  -1 999    1    1
4 999   0    1    0
0
votes

Here is a solution using data.table:-

library(data.table)
setDT(df)
df[, I.at := ifelse(at == 999 | at < 0, 1, 0)]
df[, I.Bc := ifelse(Bc == 999 | Bc < 0, 1, 0)]

This will give you:-

at  Bc I.at I.Bc
1:   1   1    0    0
2:  -9  -2    1    1
3:  -1 999    1    1
4: 999   0    1    0
0
votes

As suggested by @Ryan dplyr function mutate_all is pure magic

library(dplyr)
df %>% mutate_all(funs(I = ifelse((.)<0|(.)==999,1,0)))

output

   at  Bc at_I Bc_I
1   1   1    0    0
2  -9  -2    1    1
3  -1 999    1    1
4 999   0    1    0