user10974714
user10974714

Reputation:

Split data into named vectors

I have a data frame like this:

set.seed(123)
df <- data.frame(item = rep(c("Item1", "Item2"), c(3, 4)),
                 id = c(LETTERS[1:3], LETTERS[23:26]),
                 x = sample(7))

#    item id x
# 1 Item1  A 7
# 2 Item1  B 3
# 3 Item1  C 6
# 4 Item2  W 2
# 5 Item2  X 4
# 6 Item2  Y 5
# 7 Item2  Z 1

How can I split the data into 2 named vectors and store them in a list? Ideally names of the list are Item1 and Item2. My expected output is:

# $Item1
# A B C 
# 7 3 6 
# 
# $Item2
# W X Y Z 
# 2 4 5 1 

Upvotes: 2

Views: 96

Answers (1)

akrun
akrun

Reputation: 887078

We can use split on a named vector created from 'x' and 'id' column

with(df, split(setNames(x, id), item))
#$Item1
#A B C 
#7 3 6 

#$Item2
#W X Y Z 
#2 4 5 1 

A tidyverse option is group_split and deframe

library(dplyr)
library(purrr)
library(tibble)
df %>%
     group_split(item, keep = FALSE) %>%
     map(deframe)

Or in the devel version of dplyr

df %>%
    group_by(item) %>% 
    condense(new = deframe(cur_data())) %>% 
    pull(new)

Upvotes: 2

Related Questions