Hey there,
The idea would be to modify each modality of a list of variable (determined) of a dataframe from 0 to "NO" and from 1 to "YES". I already know how to do that for one variable at a time ... :
Id <- c("345","346","347","349","350")
Binary_Variable1 <- c(0,0,0,1,0)
df <- data.frame(Id,Binary_Variable1)
df<-df |>
mutate(Binary_Variable1 = factor(case_when(
Binary_Variable1== "0" ~ "Non",
Binary_Variable1 == "1" ~ "Oui",
TRUE ~ NA_character_)
)
)
... And I would like to create an easy function able to do so for multiple variable at once beacause my dataframe is really large
### Create a random dataframe
Id <- c("345","346","347","349","350")
Binary_Variable1 <- c(0,0,0,1,0)
Binary_Variable2 <- c(1,0,1,1,0)
Binary_Variable3 <- c(1,1,1,1,1)
Binary_Variable4 <- c(0,1,0,1,1)
df <- data.frame(Id, Binary_Variable1, Binary_Variable2, Binary_Variable3, Binary_Variable4)
### Create the function
Renomm_Variables_Binaire <- function(data_frame_source,vecteurs_variables){
for (vecteurs_variables in data_frame_source) {
data_frame_source<-data_frame_source |>
mutate(i = factor(case_when(
i == "0" ~ "Non",
i == "1" ~ "Oui",
TRUE ~ NA_character_)
}}
### Use it to change all 0 into 'No' and 1 to "Yes"
vector<- df %>% select(Binary_Variable1,Binary_Variable2,Binary_Variable3,Binary_Variable4)
Renomm_Variables_Binaire(df,vector)
I know there are some mistakes to my function because it refuses to work...
By the way, do you know any R package that helps you design your own function ?
Thank you very much in advance !