Home > database >  How can all columns of a dataframe be converted into a single list in R?
How can all columns of a dataframe be converted into a single list in R?

Time:10-01

This is an obscure request. I'm trying to do conditional formatting in flextable for an RMarkdown document, and long story short, I need a list of values derived from a dataframe.

Here's an example of a dataframe:

df <- tibble(COL_1 = c(1, 2, 3),
             COL_2 = c("A", "B", "C"),
             COL_3 = c("Peach", "Plum", "Pear"))

> df
# A tibble: 3 x 3
  COL_1 COL_2 COL_3
  <dbl> <chr> <chr>
1     1 A     Peach
2     2 B     Plum 
3     3 C     Pear 

I am looking for code to achieve the following (I'm agnostic to the type of the values):

"1", "2", "3", "A", "B", "C", "Peach", "Plum", "Pear"

Anyone have a solution? Bonus points if it's dplyr friendly.

Also, if anyone has a neat, clean way to format the color and background of a lot of values in a lot of columns in flextable, I'd appreciate the help. I doubt the solution I'm pursuing is optimal.

CodePudding user response:

unlist will helps

df %>% unlist %>% as.vector
[1] "1"     "2"     "3"     "A"     "B"     "C"     "Peach" "Plum"  "Pear" 

CodePudding user response:

Another option is to change to matrix and collapse in a vector with c.

library(magrittr)

df %>% as.matrix() %>% c
#[1] "1"     "2"     "3"     "A"     "B"     "C"     "Peach" "Plum"  "Pear" 
  • Related