Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 非对称向量表的矩阵变换_R_List_Matrix - Fatal编程技术网

R 非对称向量表的矩阵变换

R 非对称向量表的矩阵变换,r,list,matrix,R,List,Matrix,如何以有效的方式将列表对象(具有不同长度)转换为矩阵对象!以下示例阐明了上述目标: 假设您有一个结构为的列表对象: l <- list(c(1,2), c(5,7,3,11)) print(l) # [[1]] # [1] 1 2 # [[2]] # [1] 5 7 3 11 使用for循环很容易解决这个问题。你有什么想法吗?怎样才能轻松地进行这种转换?提前谢谢你 这里有一种方法: n <- max(sapply(l, length)) t(sapply(l, funct

如何以有效的方式将列表对象(具有不同长度)转换为矩阵对象!以下示例阐明了上述目标:

假设您有一个结构为的列表对象:

l <- list(c(1,2), c(5,7,3,11))
print(l)

# [[1]]
# [1] 1 2

# [[2]]
# [1]  5  7  3 11

使用for循环很容易解决这个问题。你有什么想法吗?怎样才能轻松地进行这种转换?提前谢谢你

这里有一种方法:

n <- max(sapply(l, length))
t(sapply(l, function(x) if(length(x) < n) c(x, rep(NA, n - length(x))) else x))

     [,1] [,2] [,3] [,4]
[1,]    1    2   NA   NA
[2,]    5    7    3   11
n你也可以试试

t(sapply(l, `length<-`, max(sapply(l, length))))
#     [,1] [,2] [,3] [,4]
#[1,]    1    2   NA   NA
#[2,]    5    7    3   11

<代码>(SpApple(L),长度如果您愿意使用一个包,您也可以从“Strugi”包中考虑<代码> StruxList2Mask< /Cord>:

t(sapply(l, `length<-`, max(sapply(l, length))))
#     [,1] [,2] [,3] [,4]
#[1,]    1    2   NA   NA
#[2,]    5    7    3   11
library(stringi)
l <- list(c(1,2), c(5,7,3,11))
stri_list2matrix(l, byrow = TRUE)
#      [,1] [,2] [,3] [,4]
# [1,] "1"  "2"  NA   NA  
# [2,] "5"  "7"  "3"  "11"
funDD <- function() {
  n <- max(sapply(l, length))
  t(sapply(l, function(x) if(length(x) < n) c(x, rep(NA, n - length(x))) else x))
}

funAK <- function() t(sapply(l, `length<-`, max(sapply(l, length))))

funAM <- function() {
  x <- max(vapply(l, length, 1L))
  t(vapply(l, `length<-`, numeric(x), x))
} 

funStringi <- function() stri_list2matrix(l, byrow = TRUE)

## Make a big list to test on
set.seed(1)
l <- lapply(sample(3:10, 1000000, TRUE), function(x) sample(10, x, TRUE))

system.time(out1 <- funDD())
#    user  system elapsed 
#    5.81    0.33    7.02 

library(microbenchmark)
microbenchmark(funAK(), funAM(), funStringi(), times = 10)
# Unit: seconds
#          expr      min       lq     mean   median       uq      max neval
#       funAK() 2.350877 2.499963 2.974141 3.123008 3.200545 3.418648    10
#       funAM() 1.154151 1.238235 1.337607 1.287610 1.494964 1.508884    10
#  funStringi() 2.080901 2.168248 2.352030 2.344763 2.462959 2.716910    10