- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a character data frame to numeric data frame in R?
Sometimes numerical values are recorded as character values and we need to convert them to numeric type before starting our analysis. This is also possible for a whole data frame in R. Therefore, we can use sapply function to convert the columns of the data frame to numeric type and save the output in a data frame by reading it with as.data.frame.
Example1
Consider the below data frame −
x<−sample(c("1","2","3"),20,replace=TRUE) df1<−data.frame(x) df1
Output
x 1 2 2 2 3 2 4 1 5 2 6 3 7 1 8 2 9 2 10 2 11 1 12 1 13 2 14 2 15 1 16 1 17 3 18 2 19 3 20 1
Checking the structure of df1 −
Example
str(df1)
Output
'data.frame': 20 obs. of 1 variable: $ x: chr "2" "2" "2" "1" ...
Converting the data type of columns of df1 to numeric data type −
Example
df1<−as.data.frame(sapply(df1,as.numeric)) str(df1)
Output
'data.frame': 20 obs. of 1 variable: $ x: num 2 2 2 1 2 3 1 2 2 2 ...
Example2
y1<−sample(c("254","324","220","301"),20,replace=TRUE) df2<−data.frame(y1) df2
Output
y1 1 324 2 254 3 220 4 254 5 220 6 220 7 324 8 254 9 324 10 220 11 324 12 324 13 301 14 324 15 220 16 301 17 301 18 324 19 301 20 254
Example
str(df2)
Output
'data.frame': 20 obs. of 1 variable: $ y1: chr "324" "254" "220" "254" ...
Example
df2<−as.data.frame(sapply(df2,as.numeric)) str(df2)
Output
'data.frame': 20 obs. of 1 variable: $ y1: num 324 254 220 254 220 220 324 254 324 220 ...
- Related Articles
- How to convert a data frame with categorical columns to numeric in R?
- How to convert a data frame row into character vector in R?
- How to convert an old data frame to new data frame in R?
- How to convert numeric levels of a factor into string in R data frame?
- How to convert a data frame to data.table in R?
- How to convert a list to a data frame in R?
- Convert a numeric column to binary factor based on a condition in R data frame
- How to convert a vector into data frame in R?
- How to remove a character in an R data frame column?
- How to convert alphabets to numbers in R data frame?
- How to convert the character values in an R data frame column to lower case?
- How to select only numeric columns from an R data frame?
- How to convert a data frame to a matrix if the data frame contains factor variable as strings in R?
- How to create a character vector from data frame values in R?
- How to associate a character to numbers in an R data frame column?

Advertisements