【问题标题】:How to view a list like table style in r如何在r中查看类似表格样式的列表
【发布时间】:2020-05-28 16:29:53
【问题描述】:

我面临的问题是如何将列表中的数据呈现为表格(数据框)格式,列表中的每个元素都作为字符向量,并且这些向量可能具有不同的长度,示例列表如下:

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

一般情况下,如果你使用str(sample_list),它会打印如下:

> 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"

有没有办法在R markdown(.Rmd文件)生成的文件(例如.html/.pdf)上显示结果如下(不需要严格相同,但喜欢表格样式) ?

【问题讨论】:

标签: r list datatable formatting r-markdown


【解决方案1】:

我认为主要问题是获取显示表格所需格式的数据。您可以在 R-markdown 文档中包含以下内容。

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)

【讨论】:

  • 经过测试,正确的解决方案和用空字符串填充的统一向量长度很棒,投票!
  • 变体 - data.frame(lapply(sample_list, function(x) c(x, rep('', max_len - length(x)))), check.names=FALSE)
【解决方案2】:

这是一个对 tidyverse 友好的版本:

library(dplyr)

max_len <- max(lengths(sample_list))

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多