简体   繁体   中英

R Convert list to matrix

I am trying to create a matrix from a set of list of characters as follows:

list <- list("0010","0110","1000")

I would like to convert this to a matrix with 4 columns (for each of each character of each element of the list) and 3 rows like:

在此处输入图片说明

And now I need the numbers (0s and 1s) to be recognized as numbers.

Thanks for your help!

EDIT with the output of my data, I can see now why I got that error. By the way, thank you so much for providing the answers. It looks like when using the scan function it added the name of the file as well to the list (I don't know how to fix this:

第一个元素

第二个元素

From your question, it's not quite clear if you actually mean to use a list or a vector; also, I would avoid naming variables the same as function names like list . Here's how you can solve:

# Try it with l as a list
l <- list("0010","0110","1000")
t(sapply(l, function(x) as.numeric(unlist(strsplit(x, '')))))
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    1    0
#> [2,]    0    1    1    0
#> [3,]    1    0    0    0
# Try it with l as a vector
l <- c("0010","0110","1000")
t(sapply(l, function(x) as.numeric(unlist(strsplit(x, '')))))
#>      [,1] [,2] [,3] [,4]
#> 0010    0    0    1    0
#> 0110    0    1    1    0
#> 1000    1    0    0    0

Created on 2018-11-09 by the reprex package (v0.2.1)

Explanation

sapply(x, fun) applies function fun to every element of x . So,

sapply(l, function(x) as.numeric(unlist(strsplit(x, ''))))

takes every element of l , uses strsplit(x, '') to get every individual character from that element (each "0" or "1" ), then we must unlist() because strsplit() returns a list, wrap in as.numeric() since you want numbers, and we have to wrap all of that in t() since when sapply() returns a matrix, it does it by column.

Update

From your updated question, it appears that your list elements are not in character form at all. In that case, I would follow the advice of a now deleted answer and use Reduce() and rbind()

l <- list('digist/test_digits/0_0.txt' = c(0, 0, 1, 0),
          'digist/test_digits/0_1.txt' = c(0, 1, 1, 0),
          'digist/test_digits/1_1.txt' = c(1, 0, 0, 0))
l
#> $`digist/test_digits/0_0.txt`
#> [1] 0 0 1 0
#> 
#> $`digist/test_digits/0_1.txt`
#> [1] 0 1 1 0
#> 
#> $`digist/test_digits/1_1.txt`
#> [1] 1 0 0 0
Reduce('rbind', l)
#>      [,1] [,2] [,3] [,4]
#> init    0    0    1    0
#>         0    1    1    0
#>         1    0    0    0

Created on 2018-11-09 by the reprex package (v0.2.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM