Home > database >  Is there another function faster than ifelse
Is there another function faster than ifelse

Time:11-16

I have a database that is coded with numbers instead of names. for example Less than high school = 0 High school/GED = 1 Some college/trade school = 2 Bachelor'sdegree = 3 Graduate school/advanced degree = 4

I'm using the ifelse function its working but im looking for faster way because its a big data and its time consuming

Mass_Shooter_fullDatabase$Education <- ifelse(Mass_Shooter_fullDatabase$Education==0,"Less than high school",
                                      ifelse(Mass_Shooter_fullDatabase$Education==1,"High school/GED",
                                      ifelse(Mass_Shooter_fullDatabase$Education==2,"Some college/trade school",
                                      ifelse(Mass_Shooter_fullDatabase$Education==3,"Bachelor's degree",
                                      ifelse(Mass_Shooter_fullDatabase$Education==4,"Graduate school/advanced degree",NA)))))

CodePudding user response:

I think using switch case would be much easier than if-else, Please find my answer here

library(dplyr)
Education = c(1, 1, 0, 2, 3, 4, 5)
Mass_Shooter_fullDatabase = data.frame(Education, stringsAsFactors = FALSE)

Mass_Shooter_fullDatabase %>% 
  mutate(
    Educations = case_when(
      Mass_Shooter_fullDatabase$Education == 0 ~ "Less than high school",
      Mass_Shooter_fullDatabase$Education == 1 ~ "High school/GED",
      Mass_Shooter_fullDatabase$Education == 2 ~"Some college/trade school",
      Mass_Shooter_fullDatabase$Education == 3 ~"Bachelor's degree",
      Mass_Shooter_fullDatabase$Education == 4 ~"Graduate school/advanced degree"))

Sample Output

CodePudding user response:

I think you could use switch case if such a thing exists in the language you are using. Switch case is available in java. https://www.w3schools.com/java/java_switch.asp

  •  Tags:  
  • r
  • Related