Reputation: 1097
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
Upvotes: 2
Views: 771
Reputation: 61923
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
Upvotes: 7
Reputation: 179418
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
Upvotes: 2