It is trivial to bind vectors into a data.frame with data.frame(), tibble(), or bind_cols():
library(tidyverse)
x <- 1:5
y <- letters[1:5]
d <- tibble(x, y)
What is the most efficient way to reverse this operation - i.e., take a dataframe and break it into a list with length equal to the ncol(d)? In the example above, the desired output would look like this:
> list(x = x, y = y)
$x
[1] 1 2 3 4 5
$y
[1] "a" "b" "c" "d" "e"
A single function that accomplishes this would be useful, for example, when piping a dataframe to pmap():
d %>%
break_into_list() %>% # missing function here
pmap(function(x, y) paste(x, y)) # scales to dataframe with ncol > 2
We could use unclass which also gives an attribute for 'row.names'
unclass(d)
Or with as.list
as.list(d)
If the names should be NULL, use setNames
setNames(as.list(d), NULL)
-output
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] "a" "b" "c" "d" "e"
Regarding the use of pmap, we don't need to convert to list. Assuming that we need to loop over the rows (which the pmap does)
library(dplyr)
library(purrr)
d %>%
pmap(~ f(..1, ..2))
where ..1 and ..2 are the 1st and 2nd columns that are used as input to the function where the f will be applied on each row. If there are more columns and the function requires more inputs, use ..3, ..4 etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With