Convert 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 −

 Live Demo

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

 Live Demo

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 ...
Updated on: 2021-02-05T10:08:30+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements