St4*_*096 2 r list matrix apply sparse-matrix
我在这个网站上的研究中看到了类似的问题,但不是这个确切的问题(大多数答案都涉及从列表中创建一个稀疏矩阵)。
我有一个相邻多边形列表,但希望将其转换为完整矩阵。我可以用嵌套的 for 循环笨拙地做到这一点,但我试图通过减少依赖这些来改进我的编码。所以本质上,我想从中得到:
my_list <- list("1" = c(2, 3),
"2" = 1,
"3" = 1)
Run Code Online (Sandbox Code Playgroud)
看起来像这样的东西:
# [,1] [,2] [,3]
#[1,] 0 1 1
#[2,] 1 0 0
#[3,] 1 0 0
Run Code Online (Sandbox Code Playgroud)
不诉诸于此:
for(i in 1:3{
for(j in 1:3{
[look to list to see if there is a value corresponding to (i, j),
if so insert 1, if not, zero]
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您的宝贵时间。
你可以尝试sapply
和tabulate
nbins <- max(unlist(my_list)) # 3
sapply(my_list, function(x) tabulate(x, nbins = nbins))
# [,1] [,2] [,3]
#[1,] 0 1 1
#[2,] 1 0 0
#[3,] 1 0 0
Run Code Online (Sandbox Code Playgroud)
可以在没有匿名函数的情况下编写,并进行安全检查
vapply(my_list, tabulate, nbins = nbins, FUN.VALUE = integer(nbins))
Run Code Online (Sandbox Code Playgroud)