user5946647
user5946647

Reputation:

Converting strings in list to numeric matrix

I have the following list, and I can't seem to get it converted to a numeric matrix.

> MyList
[[1]]
[1] "X4" "X3" "X2" "X5"

[[2]]
[1] "X5" "X2" "X4" "X3"

[[3]]
[1] "X4" "X3" "X2" "X5"

I tried as.matrix(MyList), but that still gives me a matrix with strings. What I'm trying to accomplish is a matrix with the numeric values, so "X4" becomes 4, "X3" becomes 3, et cetera. Any suggestions? Obviously in this code I could easily change it, with my actual code I can't change the output.

Upvotes: 1

Views: 213

Answers (1)

akrun
akrun

Reputation: 886938

We can loop through the list, use sub to remove the non-numeric characters and convert to numeric with as.numeric.

lst <- lapply(MyList, function(x) as.numeric(sub("\\D+", '', x)))
lst
#[[1]]
#[1] 4 3 2 5

#[[2]]
#[1] 5 2 4 3

#[[3]]
#[1] 4 3 2 5

If we need it to be a matrix, either

do.call(rbind, lst)

Or as @Jaap mentioned in the comments, use sapply instead of lapply and transpose the output

t(sapply(MyList, function(x) as.numeric(sub("\\D+", '', x))))

Upvotes: 2

Related Questions