Search code examples
rdataframelistdplyrmutate

How do I create a dataframe column that constitutes a list of multiple separate column entries?


I would like to create a fifth column in the below sample dataset that contains a list of columns 2:4 for each row. The desired output would be c(20,40,14) for the first row and c(13,13,0) for the second row.

My current attempt (shown in reproducible example below) yields the error "in mutate(): ℹ In argument: list_column = list(fastballs, sliders, curves). Caused by error: ! list_column must be size 2 or 1, not 3.

Any and all help appreciated.

library(tidyverse)

df <- data.frame(name = c('Bob','AJ'),
                fastballs = c(20,13),
                sliders = c(40,13),
                curves = c(14,0)) %>% 
mutate(list_column = list(fastballs,sliders,curves))

Solution

  • What about using Map

    library(dplyr)
    
    df <- data.frame(name = c('Bob','AJ'),
                     fastballs = c(20,13),
                     sliders = c(40,13),
                     curves = c(14,0)) %>% 
      mutate(list_column = Map(f=list, fastballs,sliders,curves))
    
    df