How to convert a vector to a fixed-size data frame

I have a list vector with a length of several four:

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

I want to do this to turn this list into a data frame with a 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 this?

+5
source share
2 answers

Just convert to matrix , specify 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 , since the vector input is character . We could convert a class based on 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 
+12
source

You can also try read.table on the inserted vector and specify the number of expected columns. However, it will probably not 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 
+6
source

All Articles