2

I'm trying to convert a matrix which has 46 columns and 28 rows to num, see below:

 chr [1:28, 1:46] "12.96720" "10.31482" "10.61680" "11.13120" 
"10.48705" " 9.525684" " 9.942551" ...
 - attr(*, "dimnames")=List of 2
 ..$ : chr [1:28] "BPWG " "BWBG" "GGGW" "GGPB" ...
 ..$ : NULL

However, so far when I do it the matrix loses all shape and essentially I get a list. I tried:

lapply(ggg2,function(x) as.numeric(as.character(x)))

How can I convert it so it retains the 46 columns and 28 rows?

Thanks

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Dasr
  • 777
  • 6
  • 16

1 Answers1

3

A matrix is a vector with dim attributes. So, we can directly change the class

class(gg2) <- "numeric"
gg2
#      [,1] [,2]
#BPG  12.96  1.5
#BWG  10.31  1.6
#BWBG 10.41 18.0

The issue with lapply is that it loops through each unit. For a data.frame, the unit is a column, while for vector/matrix, it is a single observation

data

gg2 <- matrix(c("12.96", "10.31", "10.41", "1.5", "1.6", "18"), 
     dimnames = list(c("BPG", "BWG", "BWBG"), NULL), 3, 2)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Can't find it now but I know I've seen recommendations to assign the `mode` instead of the `class`. Not sure what the pros/cons are... maybe `mode` works better with factors? – Gregor Thomas Oct 11 '18 at 16:48