4

我有这个数据框:

df <- structure(list(letters = c("A", "B", "C", "D"), Number = 1:4, 
    Info = c("additionalinfo", "additionalinfo", "additionalinfo", 
    "additionalinfo")), class = "data.frame", row.names = c("1", 
"2", "3", "4"))


  letters Number           Info
1       A      1 additionalinfo
2       B      2 additionalinfo
3       C      3 additionalinfo
4       D      4 additionalinfo

我尝试添加一个新列,将两列与软中断或换行符组合起来:

df %>% 
  mutate(answer = paste(Number, Info, sep = " \n" ))

期望的输出:

在此处输入图像描述

背景:在这个项目中,从数据框列中随机取一个测验问题的错误答案,而不是手动做我想用软中断换行符添加答案

它应该像第一个问题一样打印出来。哪个数字有E?: 在此处输入图像描述

4

2 回答 2

2

如果您需要该answer列而不显示整个数据框,您可以尝试

df %>% 
  mutate(answer = paste(Number, Info, sep = "\n" )) %>% 
  pull(answer) %>% 
  cat(sep = "\n")
1
additionalinfo
2
additionalinfo
3
additionalinfo
4
additionalinfo

或者,逐项

df2 <- df %>% 
  mutate(answer = paste(Number, Info, sep = "\n" ))

cat(df2$answer[1])
cat(df2$answer[2])
...
cat(df2$answer[n])
于 2022-01-30T16:25:06.833 回答
2

<br>对于闪亮渲染的文档,可以使用使用换行符的内联 HTML 。

---
title: "Tutorial"
output: learnr::tutorial
runtime: shiny_prerendered
---

#```{r setup, include=FALSE}
library(learnr); library(dplyr); library(glue)
knitr::opts_chunk$set(echo = FALSE)
df <- structure(list(letters = c("A", "B", "C", "D"), Number = 1:4, 
    Info = c("additionalinfo", "additionalinfo", "additionalinfo", 
    "additionalinfo")), class = "data.frame", row.names = c("1", 
"2", "3", "4"))
df <- df %>% mutate(answer = glue("{Number}<br>{Info}"))
#```

```{r quiz}
# This works not
quiz(
 question("Which number has E?",
       answer(df[[4]][1]),
       answer(df[[4]][2]),
       answer(df[[4]][3], correct = TRUE),
       answer(df[[4]][4])         
  ),
  # This one works
  question("Which number has E?",
       answer("1"),
       answer("4"),
       answer("5", correct = TRUE),
       answer("8")
  )
 )
于 2022-01-30T16:34:39.927 回答