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
Steve
  • 1,047
  • 1
  • 9
  • 13

2 Answers2

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
Dason
  • 60,663
  • 9
  • 131
  • 148
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
Andrie
  • 176,377
  • 47
  • 447
  • 496