首页 > 解决方案 > 如何使用 rmarkdown 将数据框转换为可打印的单个列表?

问题描述

我正在尝试使用 rmarkdown 将单个数据框转换为一组可打印的单独列表,就像电话簿中一样,但我被卡住了。我将如何打开这个数据框:

df<-mtcars[1:4,1:4]

进入这样的列表?...

Car: Mazda Rx4
MPG: 21.0
cyl: 6
disp: 160
hp: 110

Car: Datsun 710
MPG: 22.8
cyl: 4
disp: 108
hp: 93
...

标签: rr-markdown

解决方案


你所拥有的与 JSON 非常相似。如果我们把它变成一个 JSON 字符串,我们就可以清除掉你不想要的字符。这对于大型数据集并不理想

library(rjson)
library(magrittr)

df<-mtcars[1:4,1:4]

apply(df, 1, toJSON) %>% 
  setNames(paste0("Car: ", names(.), "\n")) %>% 
  gsub("(\\{|\\})", "", .) %>%  # Remove braces
  gsub(",\"", "\n", .) %>%      # replace ," with line break
  gsub("\"", "", .) %>%         # replace double quotations (could be problematic if you have text data with double quotes)
  gsub("[:]", ": ", .) %>%      # add a space after colons
  paste0(names(.), .) %>%       # put the name of the car above its data
  paste0(collapse = "\n\n") %>% # bring them into one string
  cat()

推荐阅读