简体   繁体   English

R降价:不同行的因子水平

[英]R markdown: levels of factor on different lines

I am using R markdown to create student feedback sheets, based on survey data we collect from their assessors. 我根据我们从评估员那里收集的调查数据,使用R markdown创建学生反馈表。 Input has 10 questions imported in *.csv format. 输入有10个问题,以* .csv格式导入。 Example data: 示例数据:

question <- as.factor(c(NA, NA, "response 1.", "response 2.", NA, "response 3."))

At present I am running r levels(question)[-1] in my *.rmd file which gives me this output (with ", " as separators): 目前我在我的*.rmd文件中运行r levels(question)[-1] ,它给出了我的输出(带“,”作为分隔符):

response 1., response 2., response 3.

Note that there are always some NAs so the [-1] is just to remove the NA level of the factor. 请注意,总有一些NA,因此[-1]只是为了删除因子的NA级别。

What I want is to create output with each response on a new line: 我想要的是在新行上创建每个响应的输出:

response 1. 

response 2.

response 3. 

I can do this on single forms by specifying the levels on each level ie 我可以通过指定每个级别上的级别来在单个表单上执行此操作

r levels(question)[2]

r levels(question)[3]

r levels(question)[4]

However for each question there are variable numbers of non-NA responses (1 up to 4) so I need a solution which does not explicitly have to know how many there will be. 然而,对于每个问题,存在可变数量的非NA响应(1到4),因此我需要一个没有明确知道将会有多少的解决方案。 ie same code will give desired formatting for both q1 and q2: 即相同的代码将为q1和q2提供所需的格式:

q1 <- as.factor(c(NA, NA, "response 1.", NA, NA, "response 2.")

q2 <- as.factor(c(NA, NA, "response 1.", "response 2.", "response 3.", "response 4.")

Usually I would address this with a for-loop but Markdown doesn't read code the same way as R console. 通常我会用for循环解决这个问题,但Markdown不会像R控制台一样读取代码。 Have tried as.character rather than as.factor but didn't seem to help; 尝试过as.character而不是as.factor但似乎没有帮助; calling levels(question[-1]) seemed most straighforward method to remove NA s. 调用levels(question[-1])似乎是删除NA的最直接的方法。

Thanks! 谢谢!

you can use the new line markdown operator " \\n" to put each response on a new line in your document. 您可以使用新行标记操作符" \\n"将每个响应放在文档中的新行上。

```{r}
question <- as.factor(c(NA, NA, "response 1", "response 2", NA, "response 3"))
```

`r paste0(levels(question), "  \n", collapse="")`

I had a similar question to this here 我在这里遇到了类似的问题

Note that I used cat in my comment so you could see it printed in the console. 请注意,我在评论中使用了cat ,因此您可以在控制台中看到它。 In the markdown document the rendering is taken care of so you don't need the cat 在降价文档中,渲染得到了处理,因此您不需要cat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM