Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert character of percentage into numeric in R

I run into a problem when converting character of percentage to numeric. E.g. I want to convert "10%" into 10%, but

as.numeric("10%") 

returns NA. Do you have any ideas?

like image 622
Frank Wang Avatar asked Nov 30 '11 16:11

Frank Wang


People also ask

How do I convert character to numeric in R?

To convert character to numeric in R, use the as. numeric() function. The as. numeric() is a built-in R function that creates or coerces objects of type “numeric”.

How do I change character to numeric?

Convert character to numeric. To convert character values to numeric values, use the INPUT function. new_variable = input(original_variable, informat.); The informat tells SAS how to interpret the data in the original character variable.

How do I convert a character vector to numeric in R?

numerical. To convert a character vector to a numeric vector, use as. numeric(). It is important to do this before using the vector in any statistical functions, since the default behavior in R is to convert character vectors to factors.

How do I make a percentage in R?

To calculate percent, we need to divide the counts by the count sums for each sample, and then multiply by 100. This can also be done using the function decostand from the vegan package with method = "total" .


1 Answers

10% is per definition not a numeric vector. Therefore, the answer NA is correct. You can convert a character vector containing these numbers to numeric in this fashion:

percent_vec = paste(1:100, "%", sep = "") as.numeric(sub("%", "", percent_vec)) 

This works by using sub to replace the % character by nothing.

like image 56
Paul Hiemstra Avatar answered Sep 30 '22 09:09

Paul Hiemstra