英文:
How to wrap values of a row into new line at specific character in R
问题
以下是您要翻译的内容:
我有一个带有数值的示例数据框:
```R
data <- structure(list(A = c("Date)", "Values"), B = c("2023-04-03", "Heat Capacity\nSpecific Heat Capacity\nHeat Index" )), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame" ))
这里最后一列的第二行延伸到右边。我希望每个值都在新的一行,而不添加新的行。
我的期望输出:
[![enter image description here][1]][1]
上面的表格是使用gt()
创建的:
library(gt)
data %>%
mutate(b = str_replace_all(b, "\n", "<br>")) %>%
gt() %>%
fmt_markdown(columns = TRUE)
但这对于我最终期望的输出不起作用,我想要的是一个xlsx文件,使用gt()
是行不通的。
是否可以使用dplyr
和stringr
来实现类似的结果?
请注意,我已经按您的要求只翻译了代码部分,不包括其他内容。
<details>
<summary>英文:</summary>
I have a sample dataframe with values:
data <- structure(list(A = c("Date)", "Values"), B = c("2023-04-03", "Heat Capacity\nSpecific Heat Capacity\nHeat Index" )), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame" ))
Here the 2nd row of last column extends to the right. I want the each values to be in new line without adding new rows.
My desired output:
[![enter image description here][1]][1]
The above table is created using `gt()`:
library(gt)
data %>%
mutate(b = str_replace_all(b, "\n", "<br>")) %>%
gt() %>%
fmt_markdown(columns = TRUE)
But this is not useful as my final desired output I want is in xlsx file and using `gt()` wouldn't work.
Is it possible to do anything with `dplyr` and `stringr` to achieve this similar result
[1]: https://i.stack.imgur.com/oZVrv.png
</details>
# 答案1
**得分**: 1
你可以使用`gt`包来格式化高质量的表格演示。查看[这里的`gt`介绍](https://gt.rstudio.com/articles/intro-creating-gt-tables.html)。
以下是代码,输出已省略。
``` r
suppressPackageStartupMessages({
library(tidyverse)
library(gt)
})
data <- structure(list(
A = c("日期", "数值"),
B = c("2023-04-03", "热容\n比热容\n热指数")),
row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"))
data %>%
mutate(B = gsub("\n", "<br>", B)) %>%
gt() %>%
fmt_markdown(columns = everything())
创建于2023-08-05,使用reprex v2.0.2
编辑
你可以将其导出为HTML文件,然后在Excel中打开:
data %>%
mutate(B = gsub("\n", "<br>", B)) %>%
gt() %>%
fmt_markdown(columns = everything()) %>%
as_raw_html() %>%
writeLines(con = "~/Temp/so.html")
英文:
You can use package gt
to format presentation quality tables.
See this introduction to gt
.
Here is the code, output omitted.
suppressPackageStartupMessages({
library(tidyverse)
library(gt)
})
data <- structure(list(
A = c("Date)", "Values"),
B = c("2023-04-03", "Heat Capacity\nSpecific Heat Capacity\nHeat Index" )),
row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame" ))
data %>%
mutate(B = gsub("\\n", "<br>", B)) %>%
gt() %>%
fmt_markdown(columns = everything())
<sup>Created on 2023-08-05 with reprex v2.0.2</sup>
Edit
You can export to a HTML file and open the file in Excel:
data %>%
mutate(B = gsub("\\n", "<br>", B)) %>%
gt() %>%
fmt_markdown(columns = everything()) %>%
as_raw_html() %>%
writeLines(con = "~/Temp/so.html")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论