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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With