Reputation: 133
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))
Upvotes: 3
Views: 74
Reputation: 66880
Another option is tidyr::nest
, which creates a list-column of data frames, which can be useful for some workflows but might not be what you want.
data.frame(name = c('Bob','AJ'),
fastballs = c(20,13),
sliders = c(40,13),
curves = c(14,0)) %>%
nest(list_column = -name)
df$list_column
#[[1]]
## A tibble: 1 × 3
# fastballs sliders curves
# <dbl> <dbl> <dbl>
#1 20 40 14
#
#[[2]]
## A tibble: 1 × 3
# fastballs sliders curves
# <dbl> <dbl> <dbl>
#1 13 13 0
Upvotes: 3
Reputation: 34586
Two possible options:
library(purrr)
library(dplyr)
df |>
mutate(list_column = pmap(pick(fastballs:curves), c))
or:
df |>
rowwise() |>
mutate(list_column = list(c(c_across(fastballs:curves)))) |>
ungroup()
Upvotes: 5
Reputation: 5721
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
Upvotes: 1