user12460590
user12460590

Reputation:

How to nest a dataframe in R based on columns?

I am trying to nest a dataframe (e.g. iris), so that the columnames and class (e.g. numeric, factor etc.) are in separate columns and rows and the data are in nested list. Needs to be with dplyr.

The result should look like this:

Image of desired result

Thanks a lot for your help and

best regards Alex

Upvotes: 0

Views: 346

Answers (3)

akrun
akrun

Reputation: 887108

We could create a list with data.frame call using I

data.frame(class = sapply(iris, class), 
        column_name = names(iris), nested = I(as.list(iris)))

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 173803

You could write this directly in a single line:

tibble(class = sapply(iris, class), column = names(iris), nested = as.list(iris))
#> # A tibble: 5 x 3
#>   class   column       nested      
#>   <chr>   <chr>        <named list>
#> 1 numeric Sepal.Length <dbl [150]> 
#> 2 numeric Sepal.Width  <dbl [150]> 
#> 3 numeric Petal.Length <dbl [150]> 
#> 4 numeric Petal.Width  <dbl [150]> 
#> 5 factor  Species      <fct [150]> 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can use :

out <- data.frame(class = sapply(iris, class), 
                  column_name = names(iris), row.names = NULL)
out$nested <- as.list(iris)
View(out)

enter image description here

Upvotes: 1

Related Questions