Convert Data Frame Column to Numeric in R (2 Examples)
The following R codes show how to convert data frame columns to numeric in the R programming language.
Example Data Frame
my_data <- data.frame(char = c("3", "75", "10", "8"), # Create example data fact = factor(c("3", "1", "5", "5")), stringsAsFactors = FALSE) my_data # Print data to console # char fact # 3 3 # 75 1 # 10 5 # 8 5 |
my_data <- data.frame(char = c("3", "75", "10", "8"), # Create example data fact = factor(c("3", "1", "5", "5")), stringsAsFactors = FALSE) my_data # Print data to console # char fact # 3 3 # 75 1 # 10 5 # 8 5
Check data classes of our two columns:
class(my_data$char) # Check class of first column # "character" class(my_data$fact) # Check class of second column # "factor" |
class(my_data$char) # Check class of first column # "character" class(my_data$fact) # Check class of second column # "factor"
Example 1: Conversion of Character Column to Numeric
my_data$char <- as.numeric(my_data$char) # Character column to numeric |
my_data$char <- as.numeric(my_data$char) # Character column to numeric
Check updated class of character column:
class(my_data$char) # "numeric" |
class(my_data$char) # "numeric"
Example 2: Conversion of Factor Column to Numeric
my_data$fact <- as.numeric(as.character(my_data$fact)) # Factor column to numeric |
my_data$fact <- as.numeric(as.character(my_data$fact)) # Factor column to numeric
Check updated class of factor column:
class(my_data$fact) # "numeric" |
class(my_data$fact) # "numeric"