Lampard
Lampard

Reputation: 404

How to view a list like table style in r

I am facing an issue as how to presenting data in a list as table (data frame) format, in the list each element as a character vector, and these vectors may have different length, the example list as below:

sample_list <- list("Matched x" = c("Ella", "Mila"), "Unmatched x" = c("Isla"), "Matched y" = c(), "Unmatched y" = c("Emma", "Olivia"))
sample_list

Normally, if you use str(sample_list), it will print as below:

> str(sample_list)
List of 4
 $ Matched x  : chr [1:2] "Ella" "Mila"
 $ Unmatched x: chr "Isla"
 $ Matched y  : NULL
 $ Unmatched y: chr [1:2] "Emma" "Olivia"

Is there a way to show the result on R markdown (.Rmd file) generated file (e.g .html / .pdf) as below (no need strictly same but like table style) ?
enter image description here

Upvotes: 2

Views: 2730

Answers (2)

seapen
seapen

Reputation: 394

Here is a tidyverse-friendly version:

library(dplyr)

max_len <- max(lengths(sample_list))

df <- purrr::map_df(sample_list, ~ c(., rep('', max_len - length(.))))

df %>% 
  flextable::flextable() %>% 
  flextable::autofit()

flextable_of_df_from_list

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389012

I think the main issue is to get data in the required format to display table. You can include the following in R-markdown document.

sample_list <- list("Matched x" = c("Ella", "Mila"), "Unmatched x" = c("Isla"), 
               "Matched y" = c(), "Unmatched y" = c("Emma", "Olivia"))

max_len <- max(lengths(sample_list))
df <- do.call(cbind.data.frame, c(lapply(sample_list, function(x) 
               c(x, rep('', max_len - length(x)))), stringsAsFactors = FALSE))
knitr::kable(df)

enter image description here

Upvotes: 4

Related Questions