Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a key value data frame to a list

This is the type of structure I have. There is a few thousand rows in a data frame that has similar structure to the following:

vct_names <- c("apples", "apples", "grapes", "apples", "grapes")
vct_codes <- c(23, 35, 123, 43, 156)
df_values <- data.frame(names = vct_names, codes = vct_codes)

I want to convert the data frame above into a named list. I would like to iterate through each row of the data frame above and convert this data frame to a list. The list would have the following structure:

lst_values <- list()
lst_values$apples <- c(23, 35, 43)
lst_values$grapes <- c(123, 156)

Any ideas on an elegant way to solving this problem.

like image 703
markthekoala Avatar asked Mar 14 '23 23:03

markthekoala


2 Answers

The split-function is precisely designed to do that. It works on both dataframes and on vectors as the first agument. It does this polymorphic act by being a generic function.

> methods(split)
[1] split.data.frame  split.data.table* split.Date        split.default    
[5] split.IDate*      split.POSIXct     split.zoo*       
see '?methods' for accessing help and source code

So this would be more economical:

> lst_values <- split(vct_codes, vct_names)
> lst_values
$apples
[1] 23 35 43

$grapes
[1] 123 156

In this case we are using split.default. Sometimes it's informative to print out the code, but in this case we only see some preliminary manipulation of edge cases before the data and arguments are passed to .Internal(split(seq_along(x), f)).

like image 110
IRTFM Avatar answered Mar 16 '23 17:03

IRTFM


lapply(split(df_values, df_values$names), function(z) z[,2])

$apples
[1] 23 35 43

$grapes
[1] 123 156
like image 28
sckott Avatar answered Mar 16 '23 16:03

sckott