r - 如何使用 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
...
解决方案
你所拥有的与 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()
推荐阅读
- mysql - 关于 mysqldump 和 Microsoft Azure 的问题
- excel - VBA:在另一个工作簿中调用子时使用“错误”,
- angular - 使用 web api 后在 Angular 中解包和解析模型错误
- gradle - 配置 gradle build 以抑制 javadoc 控制台警告
- r - 使用 R 登录后从网站上抓取 .txt 表
- ios - UITableView 没有在我的自定义单元格 UILabel 中正确显示数据和重用问题
- angular - 在 Angular 6 服务中获取当前路由参数的最佳方法是什么?
- asp.net - WAF is blocking ASP.NET website due to Scriptresource.axd
- node.js - Pro.find 不是猫鼬模型导出中的函数错误
- git - 需要帮助合并断开连接的 git 存储库