Reputation: 1058
Using aggregate(), I can get a data.frame like this:
V1 V2 V3
1 1 2 1
2 1 3 2, 3
3 1 4 4
4 1 5 5, 6
5 1 6 7
For V3
, it's list of vectors.
> b1$V3
$`0`
[1] 1
$`1`
[1] 2 3
$`2`
[1] 4
$`3`
[1] 5 6
$`4`
[1] 7
That surprised me since I was thinking that data.frame only have two dimensions. I can even convert it to a matrix which is pseudo-three-dimensional (though it's not real three-dimensional).
> as.matrix(b1)
V1 V2 V3
[1,] 1 2 1
[2,] 1 3 Numeric,2
[3,] 1 4 4
[4,] 1 5 Numeric,2
[5,] 1 6 7
However, I failed to create this kind of data structure in a regular way like adding a list to a data.frame/matrix. Since this kind of structure is helpful, I'd like know how it was created. Any ideas?
Upvotes: 0
Views: 61
Reputation: 193517
This kind of structure can be made using the I
function.
mydf <- data.frame(
a = 1:3,
b = I(list(1, 3:5, 6:10))
)
str(mydf)
# 'data.frame': 3 obs. of 2 variables:
# $ a: int 1 2 3
# $ b:List of 3
# ..$ : num 1
# ..$ : int 3 4 5
# ..$ : int 6 7 8 9 10
# ..- attr(*, "class")= chr "AsIs"
as.matrix(mydf)
# a b
# [1,] 1 1
# [2,] 2 Integer,3
# [3,] 3 Integer,5
You can also do this by adding the columns manually:
mydf2 <- data.frame(a = 1:3)
mydf2$b <- list(1, 3:5, 6:10)
str(mydf2)
as.matrix(mydf2)
Upvotes: 2