Home > database >  Convert 2 columns to a list in R?
Convert 2 columns to a list in R?

Time:10-23

If I have this:

 vol=list() ;df=data.frame(name=c(5,2,15,4),name=c(2,0,1,2))

I want to add this to vol, I tried but

   vol[[1]]= unclass(df) 

The output is not what i wanted

I need the out put to be like this:

$name (i need to add this title here, the first name)
name name.1
 5      2
 2      0
 15      1
 4      2

CodePudding user response:

Just wrap it in list

vol <- setNames(list(df), names(df)[1])

or create the list and set the names later

vol <- list(df)
names(vol)[1] <- names(df)[1]

Or if the object is a NULL list

vol<-list() 
vol[[names(df)[1]]] <- df

-output

> vol
$name
  name name.1
1    5      2
2    2      0
3   15      1
4    4      2

Or may also use := with dplyr::lst

vol <- dplyr::lst(!! names(df)[1] := df)

CodePudding user response:

We can also use lapply:

lapply(df, `[`)

$name
[1]  5  2 15  4

$name.1
[1] 2 0 1 2
  • Related