Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a vector into data frame with fixed dimension

Tags:

r

I have list vector with length of multiple four:

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

What I want do do is to turn that list into a data frame with dimension (M * 4):

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

How can I achieve that?

like image 749
neversaint Avatar asked Aug 24 '15 02:08

neversaint


2 Answers

Just convert to a matrix, specify the 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

The 'data.frame' columns are all character class as the input vector is character. We could convert the class based on the numeric/non-numeric values with 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
like image 136
akrun Avatar answered Oct 29 '22 03:10

akrun


You can also try read.table on the pasted vector, and specify the number of columns you expect. However, that is probably not going to be as efficient as 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
like image 23
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 29 '22 04:10

A5C1D2H2I1M1N2O1R2T1