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

时间:2015-08-24 02:05:13

标签: r

我有 list 向量,长度为四个:

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"

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:14)

只需转换为matrix,请指定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'列都是character类,因为输入vectorcharacter。我们可以使用class

基于数字/非数字值转换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

答案 1 :(得分:6)

您还可以在粘贴的向量上尝试read.table,并指定所需的列数。但是,这可能不会像matrix + data.frame + lapply那样有效:

read.table(text = paste(mylist, collapse = " "), 
           col.names = paste0("V", 1:4))
#   V1         V2    V3    V4
# 1  1 darkorange 16876 16890
# 2  2       pink  6833  7189
# 3  2       pink  9181  9279
# 4  2  darkgreen  1846  2170
str(.Last.value)
# '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