【发布时间】:2021-06-11 19:49:19
【问题描述】:
我有一个(大)由两个数字组成的字符串矩阵。我想将矩阵转换为数字矩阵,其中字符串被分成不同的列,同时保留原始矩阵的行顺序和字符串顺序。我在 R 中执行此操作,其中我主要是新手/自学成才。下面的示例输入和所需输出
input
test <- matrix[1:5,1:5]
test
col1 col2 col3 col4 col5
row1 "0,0" "0,0" "0,0" "0,0" "0,1"
row2 "0,0" "0,0" "0,0" "0,0" "0,0"
row3 "0,0" "0,0" "0,2" "0,0" "0,0"
row4 "0,0" "0,0" "0,2" "0,0" "0,0"
row5 "0,0" "0,0" "0,0" "0,0" "1,0"
desired output
col1 col1.1 col2 col2.1 col3 col3.1 col4 col4.1 col5 col5.1
row1 0 0 0 0 0 0 0 0 0 1
row2 0 0 0 0 0 0 0 0 0 0
row3 0 0 0 0 0 2 0 0 0 0
row4 0 0 0 0 0 2 0 0 0 0
row5 0 0 0 0 0 0 0 0 1 0
到目前为止,我已经尝试使用 strsplit 和 lapply/unlist,我可以制作一个不保留原始矩阵结构的矩阵,但我需要下游应用程序的原始结构。
bad output
> matrix(as.numeric(unlist(strsplit(test,","))),nrow=nrow(test))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 2 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 1 0
[3,] 0 0 0 0 0 2 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 1
[5,] 0 0 0 0 0 0 0 0 0 0
【问题讨论】: