Home > Enterprise >  Get a list from a data frame in R
Get a list from a data frame in R

Time:05-19

I have the data in the following format

col1 <- c('a','a','b','b')
col2 <- c(0.5,0.3,1,1)
df <- data.frame(col1,col2)

I want the output to be in the following format:

$a
[1] 0.5 3.0

$b
[1] 1.0 1.0

CodePudding user response:

split(df$col2, df$col1)

$a
[1] 0.5 0.3

$b
[1] 1 1

CodePudding user response:

Besides the split approach by @sindri_baldur, we can use aggregate as well

> aggregate(.~col1,df,list)$col2
[[1]]
[1] 0.5 0.3

[[2]]
[1] 1 1
  •  Tags:  
  • r
  • Related