R - Nest column values into a a single column (type list) of vectors

Viewed 168

I try to create a sequence of all columns in my dataframe, which looks like this:

df <- data.frame(label = c("ger", "at", "uk", "us"),
           a = c(1,2,3,4),
           b = c(2,3,5,1),
           c = c(5,6,2,1))

This comes close, but does not provide the desired result:

df %>% nest(data = c(a,b,c))

  label data            
  <chr> <list>          
1 ger   <tibble [1 x 3]>
2 at    <tibble [1 x 3]>
3 uk    <tibble [1 x 3]>
4 us    <tibble [1 x 3]>

Instead of a tibble, I want a vector. It should look like this:

  label data            
  <chr> <list>          
1 ger   <dbl [3]>
2 at    <dbl [3]>
3 uk    <dbl [3]>
4 us    <dbl [3]>

Does anyone know to do archieve this?

2 Answers

One dplyr and purrr option could be:

df %>%
 transmute(label,
           data = pmap(across(-label), ~ c(...)))

  label    data
1   ger 1, 2, 5
2    at 2, 3, 6
3    uk 3, 5, 2
4    us 4, 1, 1

If an unnamed vector is needed:

df %>%
 transmute(label,
           data = pmap(across(-label), ~ unname(c(...))))

We could use c_across with rowwise from dplyr

library(dplyr)
df %>%
    rowwise %>%
    transmute(label, data = list(c_across(a:c))) %>%
    ungroup

-output

# A tibble: 4 x 2
#  label data     
#  <chr> <list>   
#1 ger   <dbl [3]>
#2 at    <dbl [3]>
#3 uk    <dbl [3]>
#4 us    <dbl [3]>
Related