Search code examples
rfunctionformatting

converting multiple columns from character to numeric format in r


What is the most efficient way to convert multiple columns in a data frame from character to numeric format?

I have a dataframe called DF with all character variables.

I would like to do something like

for (i in names(DF){
    DF$i <- as.numeric(DF$i)
}

Thank you


Solution

  • You could try

    DF <- data.frame("a" = as.character(0:5),
                     "b" = paste(0:5, ".1", sep = ""),
                     "c" = letters[1:6],
                     stringsAsFactors = FALSE)
    
    # Check columns classes
    sapply(DF, class)
    
    #           a           b           c 
    # "character" "character" "character" 
    
    cols.num <- c("a","b")
    DF[cols.num] <- sapply(DF[cols.num],as.numeric)
    sapply(DF, class)
    
    #          a           b           c 
    #  "numeric"   "numeric" "character"