convert a list of class data frame objects into objects of class matrix - list

Viewed 61

I have a list of data frames. Each data frame has 6 rows and 6 columns. They are all numbers, however, all data frames have their elements as class character. Example:

$`A`
         V1       V2    V3     V4      V5       V6
V1    0.1212     0.6231 0.4431 0.3213  0.6578 0.1259
V2               2.1234 0.6532 0.9845  0.8743 0.8732
V3                      0.2314 0.7648  0.7634 0.8732
V4                             0.1234  0.6544 0.3456
V5                                     0.7653 0.9812
V6                                            0.1265

$`B`
        V1       V2    V3     V4      V5       V6
V1    0.2345     0.1234 0.5647 0.7891  0.6721 0.3259
V2               1.1334 0.4332 0.1245  0.2343 0.5332
V3                      0.2914 0.1648  0.2334 0.1232
V4                             0.1234  0.6744 0.5656
V5                                     0.3553 0.9812
V6                                            0.4665
                                                   

I would like to change all data frames of the list to class matrix (numerical). I tried:

lapply (list, data.matrix)

but the result is a list of data frames with integers. Example:

     V1   V2    V3   V4   V5   V6
V1    2    2    2    2    2    4    
V2    1    3    4    5    5    7    
V3    1    1    3    4    6    3    
V4    1    1    1    3    4    5    
V5    1    1    1    1    1    1    
V6    1    1    1    1    1    1    

Also tried to run

lapply(list, as.matrix)

however, I got a list of quoted matrices, like this:

$`A`
         V1       V2       V3       V4        V5       V6
V1    "0.1212"   "0.6231" "0.4431" "0.3213"  "0.6578" "0.1259"
V2               "2.1234" "0.6532" "0.9845"  "0.8743" "0.8732"
V3                        "0.2314" "0.7648"  "0.7634" "0.8732"
V4                                 "0.1234"  "0.6544" "0.3456"
V5                                           "0.7653" "0.9812"
V6                                                    "0.1265"
                                                   

How can I convert these data frames of my list from character class to matrix class?

2 Answers

We may loop over the list, then loop over the data.frame columns with lapply convert to numeric and assign it back to the original data.frame object and return the data.frame ('x')

list <- lapply(list, function(x) {x[] <- lapply(x, as.numeric);x})

If those are factor columns, convert to character first and then to numeric

lapply(list, function(x) {x[] <- lapply(x, function(y) as.numeric(as.character(y)))
           x})

You can convert to numeric and then reset the matrix order:

lapply(dfs, function(x) matrix(as.numeric(x), ncol = n_cols))

Data

set.seed(1L)
n_cols <- 6
n_total <- 36
a <- matrix(rnorm(n_total), ncol = n_cols)
b <- matrix(rnorm(n_total), ncol = n_cols)
a[lower.tri(a)] <- ""
b[lower.tri(b)] <- ""
dfs <- list(a, b)
Related