• Post author:
  • Post category:R Programming
  • Post last modified:August 18, 2024
  • Reading time:10 mins read
You are currently viewing How to Convert Character to Numeric in R?

How do you convert a character to numeric in R? You can use the as.numeric() function to convert the data in R programming from character to numeric. Converting character data to numeric in R is essential for statistical analysis and operations. Numeric data enables mathematical computations that cannot be done with character data, making this conversion crucial for data analysis projects. In this article, I will explain using various approaches of R how to convert data from character to numeric.

Advertisements

Key points-

  • In R, data types are fundamental concepts that define the nature of the data and specify how it can be used in computations and analyses
  • Strings representing textual data are also referred to as character data. Character data is enclosed in either single or double quotes.
  • Numeric data in R is one of the most commonly used data types and is essential for performing mathematical and statistical operations. Numeric data can be divided into two main subtypes: double and integer
  • The as.numeric() function can convert character strings, factors, and other data types to numeric format.
  • When non-numeric characters are present in the input, as.numeric() will generate a warning message indicating that NA values were introduced due to coercion.
  • The function can be applied to data frame columns, converting specific columns from character or factor types to numeric types.
  • Using apply() along with the as.numeric() can convert all columns in a data frame to a numeric type.
  • When dealing with factors, as.numeric() should be used after converting the factor to a character string to avoid unexpected results.
  • It is important to handle potential conversion errors by checking for NA values and understanding the warning messages produced during the conversion process.

as.numeric() Function

as.numeric() is a versatile function in R that efficiently converts various data types to numeric format. Effective handling of conversions plays crucial role for improving data manipulation tasks. This function allows to handle conversions across different R objects, including vectors, matrices, and data frames.

Syntax of numeric() Function

Following is the syntax of the R numeric() function.


# Synatx of the numeric() function
as.numeric(x)

Parameter

It allows only one parameter.

x: The object is converted to numeric.

Return Value

It returns the objects of numeric data type. If the input is a character string that doesn’t represent a number as.numeric() will return NA and produce a warning message.

Convert Character Vector to Numeric in R using as.numeric()

Let’s create a character vector and verify its type using the class() function. Next, we’ll pass this vector to the as.numeric() function, which will convert the data type to numeric. Finally, we’ll use the class() function again to confirm the type of the converted vector.


# Convert character to numeric using as.numeric()
# create character vector
char_vector <- c("10", "20", "30", "40", "50")
print("given character vector:")
print(char_vector)
print("Type of the vector:")
print(class(char_vector))

# Convert character vector to numeric vector
num_vector <- as.numeric(char_vector)
print("After converting character vector into numeric vector")
print(num_vector)
print("Type of the vector:")
print(class(char_vector))

Yields below output.

r convert character to numeric

Convert Character Column to Numeric in R

You can also convert the data frame column from character to numeric using the as.numeric() function. To do this, first create a data frame with character-type columns. Then, use the sapply() function to determine the data type of each column in the data frame.


# Create dataframe with 5 rows and 4 columns
df = data.frame(column1 = c('2','1','3','4','5'), column2=c('1','2','3','5','4'), 
                        column3 = as.factor(c('56','23','45','67','43')),
                        column4 = c(10, 20, 30, 40, 50))
print("Given data frame")
print(df)

print("Get the data type of each column:")
print(sapply(df, class))

Yields below output.

r convert character to numeric

After creating the data frame and determining the types of its columns, you can convert the desired column from character to numeric by passing it to the as.numeric() function. This will change the column’s data type from character to numeric. Finally, you can use the sapply() function to verify the data type of each column in the data frame.


# Convert specified charcetr column to numeric
df$column1 = as.numeric(df$column1) 

# Get the data type of each column
print("After converting the data type of each column")
print(sapply(df, class))

yields below output.

r convert character to numeric

Convert All Dataframe Columns to Numeric in R

Alternatively, you can use the as.numeric() function together with the apply() function to convert all columns of the data frame to numeric type. To achieve this, pass the data frame, 2 (which specifies the columns), and the as.numeric() function to the apply() function. This will convert the data type of all columns to numeric and return a matrix. Finally, you can use as.data.frame() to convert this matrix back into a data frame with all columns as numeric.


# Convert all data frame columns to numeric
df1 <- as.data.frame(apply(df, 2, as.numeric))
print("After converting get the datatype of each column:")
sapply(df1, class) 

# Output:
# [1] "After converting get the datatype of each column:"
#   column1   column2   column3   column4 
# "numeric" "numeric" "numeric" "numeric" 

Convert Non Numeric character to Numeric in R

If a vector contains both numeric and non-numeric characters and you want to convert it to numeric type using the as.numeric() function, the numeric characters will be converted to numeric values. For non-numeric characters, as.numeric() will return NA and produce a warning message: In eval(ei, envir) : NAs introduced by coercion.


# Create character vector
char_vector <- c("10", "20", "spark", "40", "50")
print(char_vector)

# Convert character vector to numeric vector
num_vector <- as.numeric(char_vector)
print("After converting character vector into numeric vector")
print(num_vector) 

# Output:
# [1] "After converting character vector into numeric vector"
# [1] 10 20 NA 40 50
# Warning message:
# In eval(ei, envir) : NAs introduced by coercion

Conclusion

In this article, I have explained the functionality of the as.numeric() function in R, demonstrating how it facilitates the conversion of data from character type to numeric. Additionally, I’ve explored its application on various R objects such as vectors and data frames, how it converts them with help of other functions.

References