Difference between as.numeric() and as.factor() in R

as.numeric(), as.factor() in R

Indhumathy Chelliah
PRogRamming with R

--

Photo by Karolina Grabowska: https://www.pexels.com/photo/colorful-plastic-numbers-and-mathematical-symbols-for-kids-to-learn-from-5412230/

Let’s look at the difference between as.numeric() and as.factor() in R.

as.factor()

→ It will convert the column type to factor which means we won’t be able to perform any arithmetic operations on that column. It is treated like categorical values.

Let’s look at an example. First, let’s create a dataframe with numbers column with values 1,2,3,4.

df1 <- data.frame(numbers = c(1,2,3,4))

Now let’s perform arithmetic operations on this column.

library(dplyr)
df2 <- df1 %>%
mutate(square = numbers * numbers)

Output:

Image by Author

If we convert that column “numbers” to factor, it is treated like categorical variable.

df1$numbers_factor <- as.factor(df1$numbers)

df3 <- df1 %>%
mutate(square = numbers_factor * numbers_factor)

Output:

Warning message:
There was 1 warning in `mutate()`.
ℹ In argument: `square = numbers_factor * numbers_factor`.
Caused by warning in…

--

--