[英]R Convert list to matrix
從您的問題來看,您實際上是要使用列表還是向量還不是很清楚; 另外,我會避免將變量命名為與list
等函數名稱相同的名稱。 以下是您可以解決的方法:
# 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
由reprex 包(v0.2.1) 於 2018 年 11 月 9 日創建
sapply(x, fun)
將函數fun
應用於x
每個元素。 所以,
sapply(l, function(x) as.numeric(unlist(strsplit(x, ''))))
獲取l
每個元素,使用strsplit(x, '')
從該元素中獲取每個單獨的字符(每個"0"
或"1"
),然后我們必須unlist()
因為strsplit()
返回一個列表,換as.numeric()
因為你想要數字,我們必須將所有這些都包裝在t()
因為當sapply()
返回一個矩陣時,它是按列進行的。
從您更新的問題來看,您的列表元素似乎根本不是字符形式。 在這種情況下,我會遵循現已刪除的答案的建議並使用Reduce()
和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
由reprex 包(v0.2.1) 於 2018 年 11 月 9 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.