DaniCee
DaniCee

Reputation: 3207

Remove '%' from numeric matrix

Quick question, how can I remove unwanted characters from a matrix that should be numeric?

I always get confused with apply functions, and I don't seem to be able to get this right...

Check this MWE, I have some unwanted "%" after some of the numbers, and they need to be removed. I know how to do it on a variable (column) basis, but how to apply it to the whole matrix properly?

> a=matrix(c('7%','11%',22,'65%',7,8,'1%','77%','34%'), ncol=3)
> a
     [,1]  [,2]  [,3]
[1,] "7%"  "65%" "1%"
[2,] "11%" "7"   "77%"
[3,] "22"  "8"   "34%"
> as.numeric(sub("%$","",a[,1]))
[1]  7 11 22

Expected output:

> a
     [,1] [,2] [,3]
[1,]    7   65    1
[2,]   11    7   77
[3,]   22    8   34

Upvotes: 2

Views: 54

Answers (2)

akrun
akrun

Reputation: 886938

We could do this in a single step

matrix(readr::parse_number(a), dim(b))
#     [,1] [,2] [,3]
#[1,]    7   65    1
#[2,]   11    7   77
#[3,]   22    8   34

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388797

On matrix you can apply the transformation directly :

b <- a
b <- as.numeric(sub('%$','', b))
dim(b) <- dim(a)
b
#     [,1] [,2] [,3]
#[1,]    7   65    1
#[2,]   11    7   77
#[3,]   22    8   34

Upvotes: 3

Related Questions