开发者

List of List in Data Frame

I have a data that is generated like this:

> dat1 <- data.frame(V1 = rep(1, 5), V2 = sample(c(40:45), 5))
> dat2 <- data.frame(V1 = sample(c(0,1), 5, replace = TRUE), V2 = sample(c(40:45), 5, replace = TRUE))

What I want to do is to obtain a data frame that contain list of list.

> hiv
$hiv.dat1
$hiv.dat1$V1[[1]]
[1] 1 1 1 1 1

$hiv.dat1$V2[[1]]
[1] 41 42 43 40 44


$hiv.dat2
$hiv.dat2$V1[[1]]
[1] 0 1 1 0 0

$hiv.dat2$V2[[1]]
[1] 42 43 40 44 43

But why this line of command failed to create that?

开发者_如何学编程> hiv <- list(hiv.dat1 = as.list(dat1), hiv.dat2 = as.list(dat2))

Especially it gives "$hiv.dat1$V1" instead of "$hiv.dat1$V1[[1]]".

How can we correct that? I need this particular data structure required for a specific package (ROCR).


It seems you want each element of the data frame to become its own list (of length one); your code instead makes each data frame into a list containing the elements of the data frame. You need to apply the list function to each element individually with lapply.

hiv <- list(hiv.dat1 = lapply(dat1, list), hiv.dat2 = lapply(dat2, list))


Only list type can be

  • nested (ie recurse)

  • contain objects of different type and length

So in short no nesting of data frames, but you can pile different data frames inside a list.

(And please do not crosspost here and on r-help.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜