拆分变量并在其间插入NA

JSP*_*JSP 1 variables split r dataframe

我有一个看起来像这样的变量:

Var
[1] 3, 4, 5     2, 4, 5     2, 4     1, 4, 5
Run Code Online (Sandbox Code Playgroud)

我需要将其拆分为数据框,如下所示:

V1   V2   V3   V4   V5
NA   NA   3    4    5
NA   2    NA   4    5
NA   2    NA   4    NA
1    NA   NA   4    5
Run Code Online (Sandbox Code Playgroud)

不幸的是,我找不到能解决我问题的帖子.有谁知道我怎么能这样做?非常感谢你提前!

编辑:我找到了一个基于你的答案的解决方案,并在下面发布.

Edit2:我使用Ananda的解决方案提高了代码的效率.

the*_*ail 5

使用矩阵索引:

Var <- list(c(3,4,5),c(2,4,5),c(2,4),c(1,4,5))
unVar <- unlist(Var)
out <- matrix(NA, nrow=length(Var), ncol=max(unVar))

out[cbind(rep(seq_along(Var),sapply(Var,length)),unVar)] <- unVar
# and if you're using the new version of R, you can simplify a little:
out[cbind(rep(seq_along(Var),lengths(Var)),unVar)] <- unVar

#     [,1] [,2] [,3] [,4] [,5]
#[1,]   NA   NA    3    4    5
#[2,]   NA    2   NA    4    5
#[3,]   NA    2   NA    4   NA
#[4,]    1   NA   NA    4    5
Run Code Online (Sandbox Code Playgroud)