user2350366
user2350366

Reputation: 511

Extracting data from data frame with lists as elements?

I have the following data frame:

Test <- data.frame(matrix(NA, nrow = 1, ncol = 3))
Test$X1 <- list(c(0,1))
Test$X2 <- list(c(2,3))
Test$X3 <- list(c(4,5))

It allows me to place lists inside of elements:

Test
    X1   X2   X3
1 0, 1 2, 3 4, 5

Its been kept simple here, but this would be n by m data frame. This is passed into several subroutines. Now I need to extract that element information. To do this I loop over the columns/rows. I've found that once in the subroutine I needed to do

Test <- as.list(Test)

Test
$X1
$X1[[1]]
[1] 0 1


$X2
$X2[[1]]
[1] 2 3


$X3
$X3[[1]]
[1] 4 5

For the subroutine to make sense of this object. And I now need to extract the data. To do this I can use

dummy_list <- Test$X2[[1]]
print(dummy_list[1])
print(dummy_list[2])

Which gives the values 2 and 3 as expected. I need to automate this so that I can loop over every pair of values, i.e every element in the data frame. In this example then I would need: Test$X1[[1]], Test$X2[[1]] and Test$X3[[1]]. How do I loop over the column name Xi? All attempts so far have failed. I also looked at transposing the data and fixing the column name (X1) then I'd be able too loop over Test$X1[[i]], but the Test gives

     X1     X2     X3    
[1,] List,1 List,1 List,1

which is not what I wanted. Anyone know how to do this?

Upvotes: 0

Views: 52

Answers (1)

Sotos
Sotos

Reputation: 51592

Assuming that,

Test1 <- rbind(Test, Test)

then to keep your attempt,

sapply(Test1, function(i) sapply(seq(nrow(Test1)), function(j) i[[j]]))

#     X1 X2 X3
#[1,]  0  2  4
#[2,]  1  3  5
#[3,]  0  2  4
#[4,]  1  3  5

However, this becomes ridiculously simple with unnest from tidyr,

tidyr::unnest(Test1)

#which outputs a tibble
# A tibble: 4 × 3
#     X1    X2    X3
#  <dbl> <dbl> <dbl>
#1     0     2     4
#2     1     3     5
#3     0     2     4
#4     1     3     5 

It can also be achieved using matrix

matrix(unlist(Test1), ncol = ncol(Test1))

#which outputs a matrix
#      [,1] [,2] [,3]
#[1,]    0    2    4
#[2,]    1    3    5
#[3,]    0    2    4
#[4,]    1    3    5

Upvotes: 1

Related Questions