Search code examples
rdataframelevels

Edit the levels of several columns at once in R


I am trying to set the levels of several factor columns to the following values "No" and "Yes". I use the following code but it does not work

binaryCol <- c(5:10, 15:19, 21:26, 30:32) # position of the columns for which I want to change the factors
for( i in binaryCol) {levels(df[,i])<- c("No","Yes")}

Any help would be appreciated


Solution

  • Your code works just fine with a simple example:

    binaryCol <- c(1,3)
    df <- data.frame(Var1=factor(1:0), Var2=1:2, Var3=factor(0:1))
    #  Var1 Var2 Var3
    #1    1    1    0
    #2    0    2    1
    
    for(i in binaryCol) { levels(df[,i]) <- c("No","Yes") }
    df
    #  Var1 Var2 Var3
    #1  Yes    1   No
    #2   No    2  Yes
    

    Alternatively, use lapply to apply a function to your selected factor columns:

    df[binaryCol] <- lapply(df[binaryCol], function(x) {levels(x) <- c("No","Yes"); x })
    
    df
    #  Var1 Var2 Var3
    #1  Yes    1   No
    #2   No    2  Yes
    

    Or if you want to be tricky:

    df[binaryCol] <- lapply(df[binaryCol], `levels<-`, c("No","Yes") )