如何将矢量转换为具有固定维度的数据帧

我有长度为四的列表向量:

mylist <- c("1", "darkorange", "16876", "16890", "2", "pink", "6833", "7189", 
"2", "pink", "9181", "9279", "2", "darkgreen", "1846", "2170"
)

我想要做的是将该列表转换为数据框
尺寸(M * 4):

V1    V2           V3     V4
"1" "darkorange" "16876" "16890" 
"2" "pink"       "6833"  "7189" 
"2" "pink"       "9181"  "9279" 
"2" "darkgreen"  "1846"  "2170"

我怎样才能做到这一点?

最佳答案
只需转换为矩阵,指定ncol

m1 <- matrix(mylist, ncol=4, byrow=TRUE)
d1 <- as.data.frame(m1, stringsAsFactors=FALSE)
d1
#  V1         V2    V3    V4
#1  1 darkorange 16876 16890
#2  2       pink  6833  7189
#3  2       pink  9181  9279
#4  2  darkgreen  1846  2170

‘data.frame’列都是字符类,因为输入向量是字符.我们可以使用type.convert基于数字/非数字值转换类

d1[] <- lapply(d1, type.convert)
str(d1) 
#'data.frame':  4 obs. of  4 variables:
#$V1: int  1 2 2 2
#$V2: Factor w/ 3 levels "darkgreen","darkorange",..: 2 3 3 1
#$V3: int  16876 6833 9181 1846
#$V4: int  16890 7189 9279 2170

转载注明原文:如何将矢量转换为具有固定维度的数据帧 - 代码日志