Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nest all columns by row

Tags:

r

tidyr

Here is a reproducible example where I have used an auxiliary column (temp) to generate the nested data column.

How can I get the same result without using an auxiliary column? I tried using group_by_all but it didn't work. (So, I'm also not sure that I understand what the use of the group_by_all function is)

df <- structure(
  list(
    Var1 = c(0L, 1L, 2L, 3L, 0L, 1L, 2L, 3L, 0L, 1L, 
             2L, 3L, 0L, 1L, 2L, 3L, 0L, 1L, 2L, 3L,
             0L, 1L, 2L, 3L),
    Var2 = c(0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 2L, 2L,
             2L, 2L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L,
             2L, 2L, 2L, 2L), 
    Var3 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
             0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
             1L, 1L,1L, 1L)
  ),
  .Names = c("Var1", "Var2", "Var3"),
  out.attrs = structure(
    list(
      dim = c(4L, 3L, 2L), 
      dimnames = structure(
        list(
          Var1 = c("Var1=0","Var1=1", "Var1=2", "Var1=3"), 
          Var2 = c("Var2=0", "Var2=1","Var2=2"), 
          Var3 = c("Var3=0", "Var3=1")), 
          .Names = c("Var1","Var2", "Var3")
        )
      ),
    .Names = c("dim", "dimnames")
  ), 
  class = "data.frame", row.names = c(NA,-24L)
)

df$temp <- 1:nrow(df)
df %>% group_by(temp) %>% nest %>% select(-temp) 
like image 257
Brani Avatar asked Oct 22 '17 11:10

Brani


1 Answers

We could use group_split to split on every row and use nest on each row.

library(tidyverse)

df %>%
  group_split(row_number(), keep = FALSE) %>%
  map_df(nest)

# A tibble: 24 x 1
#   data            
#   <list>          
# 1 <tibble [1 × 3]>
# 2 <tibble [1 × 3]>
# 3 <tibble [1 × 3]>
# 4 <tibble [1 × 3]>
# 5 <tibble [1 × 3]>
# 6 <tibble [1 × 3]>
# 7 <tibble [1 × 3]>
# 8 <tibble [1 × 3]>
# 9 <tibble [1 × 3]>
#10 <tibble [1 × 3]>
# … with 14 more rows

With keep = FALSE we do not include the grouping column which is row_number() here.

Now instead of row_number, we can use different variations to split it by row.

#Option 2
df %>% group_split(1:nrow(df), keep = FALSE) %>% map_df(nest)

#Option 3
df %>% group_split(seq_len(n()), keep = FALSE) %>% map_df(nest)

#Option 4
df %>% group_split(seq_len(nrow(df))) %>% map_df(nest)
like image 153
Ronak Shah Avatar answered Sep 18 '22 06:09

Ronak Shah