【问题标题】:Prevent last word on a line from being split across lines on R Markdown report防止一行上的最后一个单词在 R Markdown 报告中跨行拆分
【发布时间】:2018-06-28 17:04:46
【问题描述】:

我想使用 R Markdown 打印对调查问题的开放式回复(任意长度的字符串),并且我希望所有回复都在同一个标​​题下。例如,问题“这位老师如何改进?”存储在名为d 的数据框中,并存储在名为x 的变量中。

这是一个例子:

---
title: "Teacher Survey"

output:
  html_document 
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
d <- data.frame(id = (1:2), x =c("Test to see if word gets split: I kind 
of think that for this teacher to improve they will have make a better 
attempt to attend to the needs of all the students in the classroom", 
"For this teacher to improve they will have make a better attempt to 
attend to the needs of all the students in the classroom"), 
stringsAsFactors = FALSE)
```
###How can this teacher improve
```{r comment=NA}
print(d$x)
```

第一个响应在第一行打印“bette”,在第二行打印“r”,而不是在一行上打印“better”。我怎样才能使它“更好”地打印在一行上?

【问题讨论】:

  • 你的输出去哪儿了? (pdf、笔记本、html、word 等)。
  • 输出为html。
  • 你能提供一个minimal reproducible example吗?

标签: r r-markdown


【解决方案1】:

我喜欢使用cat() 而不是print(),并为块指定results='asis'

这样,文本就直接通过html渲染出来了。

###How can this teacher improve
```{r comment=NA, results='asis'}
cat(d$x)
```

而不是 &lt;code/&gt; 通过 html 阻止。

这是第一张和第二张图片之间的 html 比较。注意第一种方式以&lt;p&gt;Test开头,而第二种方式是&lt;pre&gt;&lt;code&gt;[1] &amp;quot;

<div id="how-can-this-teacher-improve" class="section level3">
<h3>How can this teacher improve</h3>
<p>Test to see if word gets split: I kind of think that for this teacher to improve they will have make a better attempt to attend to the needs of all the students in the classroom For this teacher to improve they will have make a better attempt to attend to the needs of all the students in the classroom</p>
</div>

<div id="how-can-this-teacher-improve" class="section level3">
<h3>How can this teacher improve</h3>
<pre><code>[1] &quot;Test to see if word gets split: I kind \nof think that for this teacher to improve they will have make a better \nattempt to attend to the needs of all the students in the classroom&quot;
[2] &quot;For this teacher to improve they will have make a better attempt to \nattend to the needs of all the students in the classroom&quot;                                                       </code></pre>
</div>

【讨论】:

  • results = 'asis' 非常有帮助。我不能使用 cat 因为它结合了多个受访者的答案。通过使用{r comment=NA, results='asis'} for (i in 1:nrow(d)){ writeLines(d[i, 2]) cat("\n") } ,我能够获得我喜欢的格式
  • 酷。另一种选择类似于cat(" ", d$x, sep="\n1. ")。在这种情况下,它将位于编号列表中,但您可以使用任何降价或 html 样式/装饰。
猜你喜欢
  • 2021-11-16
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多