给出N个元素的向量:
LETTERS[1:10]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
如何获得data.table/frame
(df
)如下?
>df
one two
A B
C D
E F
G H
I J
概括我想知道给定一个向量分割如下:
[A B C],[D E],[F G H I J]
并获得:
V1 V2 V3 V4 V5
A B C NA NA
D E NA NA NA
F G H I J
答案 0 :(得分:1)
一种选择是matrix
方式
as.data.frame(matrix(LETTERS[1:10], ncol=2,byrow=TRUE,
dimnames = list(NULL, c('one', 'two'))), stringsAsFactors=FALSE)
# one two
#1 A B
#2 C D
#3 E F
#4 G H
#5 I J
如果我们需要创建索引,我们可以gl
使用split
vector
和rbind
do.call(rbind, split(v1, as.integer(gl(length(v1), 2, length(v1)))))
,其中
v1 <- LETTERS[1:10]
基于OP的帖子中的更新
lst <- split(v1, rep(1:3, c(3, 2, 5)))
do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
# [,1] [,2] [,3] [,4] [,5]
#1 "A" "B" "C" NA NA
#2 "D" "E" NA NA NA
#3 "F" "G" "H" "I" "J"
或其他
library(stringi)
stri_list2matrix(lst, byrow = TRUE)
如果我们使用'splitVec'
lst <- split(v1, cumsum(seq_along(v1) %in% splitVec))
然后按上述步骤进行