What to do if numeric values are being read as character in R?


If the numeric values are being read as character then we need to convert them into numeric values by using the function as.numeric. For example, if we have a data frame called df that contains a column say x which has numerical values stored in character format then we can convert them into numeric values using the command as.numeric(df$x).

Example

Consider the below data frame −

 Live Demo

x1<-sample(c("1","2","3","4","5","6","7","8","9","10"),20,replace=TRUE)
y1<-rnorm(20,32,3.5)
df1<-data.frame(x1,y1)
df1

Output

    x1     y1
1   2   38.41928
2   2   28.34428
3  10   30.46244
4   8   36.94547
5  10   33.09146
6   5   30.99976
7   9   35.00749
8   1   33.06580
9   9   29.80171
10  6   32.88228
11  3   32.40530
12  9   30.62869
13 10   30.71713
14  5   34.77270
15  5   29.15327
16  4   28.82024
17  6   32.74733
18  7   30.78099
19  2   29.03388
20  5   31.97420

Example

str(df1)

Output

'data.frame': 20 obs. of 2 variables:
$ x1: chr "2" "2" "10" "8" ...
$ y1: num 38.4 28.3 30.5 36.9 33.1 ...

Converting values in x1 column of df1 to numeric −

Example

df1$x1<-as.numeric(df1$x1)
str(df1)

Output

'data.frame': 20 obs. of 2 variables:
$ x1: num 2 2 10 8 10 5 9 1 9 6 ...
$ y1: num 38.4 28.3 30.5 36.9 33.1 ...

Example

 Live Demo

x2<-sample(c("101","102","103","104","105","106","107","108"),20,replace=TRUE)
y2<-rpois(20,5)
df2<-data.frame(x2,y2)
df2

Output

   x2  y2
1  105  2
2  105  4
3  108  3
4  107  2
5  104  5
6  106  2
7  105  5
8  101  4
9  102  6
10 106  2
11 108  3
12 106  4
13 102  4
14 106  7
15 104  3
16 103 10
17 105  3
18 104  1
19 102  4
20 102 10

Example

str(df2)

Output

'data.frame': 20 obs. of 2 variables:
$ x2: chr "105" "105" "108" "107" ...
$ y2: int 2 4 3 2 5 2 5 4 6 2 ...

Converting values in x2 column of df2 to numeric −

Example

df2$x2<-as.numeric(df2$x2)
str(df2)

Output

'data.frame': 20 obs. of 2 variables:
$ x2: num 105 105 108 107 104 106 105 101 102 106 ...
$ y2: int 2 4 3 2 5 2 5 4 6 2 ...

Updated on: 16-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements