0

I have a dataframe with many columns nested tibbles and other normal columns. I now want to nest all of the columns that are not a list. So the end result will be a data frame in which all columns are lists. I can do this by typing out the names of each variables. But I am basically looking for a nest_if command that would allow me to capture all the variables that are not in a list

# I know this isn't a real function
nest_if(negate(is.list))


Progman
  • 16,827
  • 6
  • 33
  • 48
dano_
  • 303
  • 1
  • 8
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 25 '21 at 06:35

1 Answers1

0

You can get the names of the non list columns and then nest by name. Something like this:

library(dplyr)
library(tidyr)

# example df
df <- tibble(
  vec_col1 = 1:10,
  vec_col2 = 11:20,
  list_col1 = as.list(1:10),
  list_col2 = as.list(11:20)
)

# get non list columns
col_classes <- sapply(df, class)
non_list_cols <- names(col_classes)[col_classes != "list"]

# nest by column name
df %>% 
  nest(data = matches(non_list_cols))

# # A tibble: 10 x 3
# list_col1 list_col2 data            
# <list>    <list>    <list>          
#   1 <int [1]> <int [1]> <tibble [1 × 2]>
#   2 <int [1]> <int [1]> <tibble [1 × 2]>
#   3 <int [1]> <int [1]> <tibble [1 × 2]>
#   4 <int [1]> <int [1]> <tibble [1 × 2]>
#   5 <int [1]> <int [1]> <tibble [1 × 2]>
#   6 <int [1]> <int [1]> <tibble [1 × 2]>
#   7 <int [1]> <int [1]> <tibble [1 × 2]>
#   8 <int [1]> <int [1]> <tibble [1 × 2]>
#   9 <int [1]> <int [1]> <tibble [1 × 2]>
#  10 <int [1]> <int [1]> <tibble [1 × 2]>
yogevmh
  • 316
  • 1
  • 5