fatoddsun
fatoddsun

Reputation: 249

From list of characters to matrix/data-frame of numeric (R)

I have a long list, whose elements are lists of length one containing a character vector. These vectors can have different lengths.

The element of the vectors are 'characters' but I would like to convert them in numeric, as they actually represent numbers.

I would like to create a matrix, or a data frame, whose rows are the vectors above, converted into numeric. Since they have different lengths, the "right ends" of each row could be filled with NA.

I am trying to use the function rbind.fill.matrix from the library {plyr}, but the only thing I could get is a long numeric 1-d array with all the numbers inside, instead of a matrix.

This is the best I could do to get a list of numeric (dat here is my original list):

dat<-sapply(sapply(dat,unlist),as.numeric)

How can I create the matrix now? Thank you!

Upvotes: 1

Views: 1912

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193637

I would do something like:

library(stringi)
temp <- stri_list2matrix(dat, byrow = TRUE)
final <- `dim<-`(as.numeric(temp), dim(temp))

The basic idea is that stri_list2matrix will convert the list to a matrix, but it would still be a character matrix. as.numeric would remove the dimensional attributes of the matrix, so we add those back in with:

`dim<-` ## Yes, the backticks are required -- or at least quotes

POC:

dat <- list(1:2, 1:3, 1:2, 1:5, 1:6)
dat <- lapply(dat, as.character)

dat
# [[1]]
# [1] "1" "2"
# 
# [[2]]
# [1] "1" "2" "3"
# 
# [[3]]
# [1] "1" "2"
# 
# [[4]]
# [1] "1" "2" "3" "4" "5"
# 
# [[5]]
# [1] "1" "2" "3" "4" "5" "6"

library(stringi)
temp <- stri_list2matrix(dat, byrow = TRUE)
final <- `dim<-`(as.numeric(temp), dim(temp))
final
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    2   NA   NA   NA   NA
# [2,]    1    2    3   NA   NA   NA
# [3,]    1    2   NA   NA   NA   NA
# [4,]    1    2    3    4    5   NA
# [5,]    1    2    3    4    5    6

Upvotes: 2

Related Questions