Wednesday, May 13, 2015

Data wrangling (1): Conversion of the list and data frame types



Abstract: Conversion of a dataset between the list type and the data frame type.


Convert the data frame to list using the function as.list(). Convert the list to the data frame using do.call().
> #convert data frame into list
> #data frame
> df<-as.data.frame(matrix(1:12, nrow=3))
> df
V1 V2 V3 V4
1 1 4 7 10
2 2 5 8 11
3 3 6 9 12
> #conversion by columns
> my.list<-as.list(df)
> my.list
$V1
[1] 1 2 3

$V2
[1] 4 5 6

$V3
[1] 7 8 9

$V4
[1] 10 11 12

>
> #convert list to data frame
> do.call(cbind, my.list)
V1 V2 V3 V4
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12

The R package plyr provide the function laply() for convert the list with different length to a data frame
> #convert list with different length into data frame
> library(plyr)
> #
> my.list<-list('a'=c(1,3,4), 'b'=c(1,2,6,7))
> my.list
$a
[1] 1 3 4

$b
[1] 1 2 6 7

> my.df<-t(ldply(.data=my.list, .fun=rbind))
> colnames(my.df)<-my.df[1,]
> my.df<-my.df[-1,]
> my.df
a b
1 "1" "1"
2 "3" "2"
3 "4" "6"
4 NA " 7"


Writing date: 20150511





No comments:

Post a Comment