简体   繁体   中英

Convert nested list to data frame while preserving column types

Given a list, b01 , of lists: tp01 , tp02 , tp03 , where each tp stores a specific type of data, how do I extract the class of each tp ?

The goal is to return a single data frame that preserves the original variable's type (eg int, char). I was thinking of extracting the classes of each tp and storing them, then overwriting the data frame's classes with those stored classes.

In the example below, the resulting data frame has 3 variables that are considered Factor . I would like them to be considered int , char , int .

I tried the following without luck:

str(as.data.frame(lapply(b01,unlist)))
str(sapply(as.data.frame(lapply(b01,unlist)),class))
lapply(b01,unlist)
sapply(str(lapply(b01,unlist)),unlist)

MWE:

set.seed(1)
tp01 <- list(sample(seq(0,100),10))
set.seed(2)
tp02 <- list(sample(seq(0,100),10))
tp03 <- list(letters[c(sample(seq(0,26),10))])
b01 <- list(tp01, tp02, tp03)

df <- as.data.frame(matrix(unlist(lapply(all,unlist)),
    nrow=length(unlist(b01[1]))*length(all)))
> df
   V1 V2 V3
1  26  q 18
2  37  j 70
3  56  t 56
4  89  c 16
5  19  g 91
6  86  y 90
7  97  w 12
8  62  v 78
9  58  r 43
10  5  b 50
11 18 26  q
12 70 37  j
13 56 56  t
14 16 89  c
15 91 19  g
16 90 86  y
17 12 97  w
18 78 62  v
19 43 58  r
20 50  5  b

str(df)
'data.frame':   20 obs. of  3 variables:
 $ V1: Factor w/ 19 levels "12","16","18",..: 5 6 10 16 4 15 19 12 11 8 ...
 $ V2: Factor w/ 20 levels "19","26","37",..: 15 14 17 12 13 20 19 18 16 11 ...
 $ V3: Factor w/ 20 levels "12","16","18",..: 3 7 6 2 10 9 1 8 4 5 ...

You can do this with lapply and as.data.frame:

names(b01) <- c("tp01","tp02","tp03")  #optional
first.step <- lapply(b01, unlist) 
second.step <- as.data.frame(first.step, stringsAsFactors = F) 

See unlist() documentation for info on coercion with that step. The stringsAsFactors = F argument will preserve the character vector in the second step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM