Posts

Showing posts with the label Formatting

Converting Multiple Columns From Character To Numeric Format In R

Answer : 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" If you're already using the tidyverse, there are a few solution depending on the exact situation. Basic if you know it's all numbers and doesn't have NAs library(dplyr) # solution dataset %>% mutate_if(is.character,as.numeric) Test cases df <- data.frame( x1 = c('1','2','3'), x2 = c('4','5','6'), x3 = c(...