2

I've parsed through a file to extract certain values. A column contains a percentage with the symbol. Is there any way to remove that "%" character?

From this:

98.9% 23 43 92.2% 342 34 98.9% 53 53 82.2% 32 76 97.9% 83 45 92.9% 92 23 

to:

98.9 23 43 92.2 342 34 98.9 53 53 82.2 32 76 97.9 83 45 92.9 92 23 

2 Answers 2

7

You say in the title that you have a matrix - in which case everything in the matrix should be 'character' already. Use gsub to replace % with nothing.

> j <- matrix(c("1%", "2%", 3, 4), ncol = 2) > j [,1] [,2] [1,] "1%" "3" [2,] "2%" "4" > gsub("%", "", j) [,1] [,2] [1,] "1" "3" [2,] "2" "4" 

if you want it to be numeric you could use apply along with as.numeric

> apply(gsub("%", "", j), 1, as.numeric) [,1] [,2] [1,] 1 2 [2,] 3 4 
Sign up to request clarification or add additional context in comments.

1 Comment

Seems like it's inherent in gsub.
2

Use gsub to substitute the % for an empty string, then convert to numeric:

x <- c("98.9%", "92.2%", "98.9%", "82.2%", "97.9%", "92.9%") as.numeric(gsub("%", "", x)) [1] 98.9 92.2 98.9 82.2 97.9 92.9 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.