Search code examples
rlistnumeric

Convert dataframe to list with numeric vectors in r


I would like to transform values from a dataset to a list as numeric values.

Here is a sample dataset:

df <- data.frame(
  a = c(5.5, 6, 7),
  b = c(1.1, 2.5, 3.5))

# convert dataframe to list
df.list <- split(df, seq(nrow(df)))

enter image description here

The list looks like the above in the R environment. My desired output in the R environment is like below by getting rid of the $s, as, and bs.

enter image description here

I tried this below but it did not really give what I wanted.

for (i in 1:length(df.list)) {
  df.list[[i]] <- lapply(df.list[[i]], function(x) as.numeric(as.character(df.list[[i]])))
  
}

enter image description here

Does ANyone have any ideas?

Thanks!


Solution

  • We can use asplit from base R. Specify the MARGIN as 1 for rows and 2 for column wise split

    out <- lapply(asplit(unname(df), 1), as.vector)
    str(out)
    #List of 3
    #$ : num [1:2] 5.5 1.1
    #$ : num [1:2] 6 2.5
    #$ : num [1:2] 7 3.5
    

    Or another option is apply

    out2 <- do.call(c, apply(unname(df), 1, list)) 
    identical(out, out2)
    #[1] TRUE
    

    From the OP's split, we can unlist the list elements

    out3 <- lapply(unname(df.list), unlist, use.names = FALSE)
    identical(out, out3)
    #[1] TRUE