dimanche 15 août 2021

How to make a function in R to recode a variable into new binary columns? (with ifelse statement)

I want to make a function to recode values within a variable to binary 0 and 1 using ifelse. Suppose I have this dataset:

df <- data.frame(
        id = 1:10,
        region = rep(c("Asia", "Africa", "Europe", "America"), length = 10)
        )

This is the output that I want:

enter image description here

However, I want to create those columns by using function, so I just have to enter the data and variable to the function. This is as far as I get:

binary <- function(data2, var, value){
        for(i in 1:nrow(data2)){        
            val <- ifelse(data2[data2[var] == value, 1, 0)
            data2 <- cbind(data2, val)
            }
        }

Does anyone know how to use the ifelse function within the for loop and function in R? Any help is much appreciated. Thank you.

Aucun commentaire:

Enregistrer un commentaire