How to convert a list to a data frame in R?


Consider the below list −

> List <- replicate(
   20,
   list(sample(letters, 10)),
   simplify = FALSE
)

This list can be converted to a data frame using below code −

> df <- data.frame(matrix(unlist(List), nrow=length(List), byrow=T))
> df
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 x c t g d l j y i q
2 s k u j i w x o p n
3 h p e c y m o d z s
4 c f e d n w v b k h
5 u y g j i m l x k s
6 q k f v y b c i x z
7 x i v m f j h t g b
8 c z s y k d f e j h
9 y v l x i q s o h t
10 s n i l c x e h q d
11 w j l y k a p v r g
12 l s q o n f p z u i
13 b d l z n i q p v c
14 f i d j a p z k e w
15 y a n p k g x f v b
16 k o c q u x i v e b
17 c u q o a e j l y v
18 j e o y w h q i b z
19 s j k x w l g z d u
20 h k r e x w f n c v

The above code will convert all the character variables to factors as shown below −

> df$X1
[1] x s h c u q x c y s w l b f y k c j s h
Levels: b c f h j k l q s u w x y

But we can avoid this by using stringsAsFactors function −

> df <- data.frame(matrix(unlist(List), nrow=20, byrow=T),stringsAsFactors=FALSE)
> df$X1
[1] "x" "s" "h" "c" "u" "q" "x" "c" "y" "s" "w" "l" "b" "f" "y" "k" "c" "j" "s"
[20] "h"

Updated on: 06-Jul-2020

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements