r - Rmarkdon中单独代码块中的拆分功能
问题描述
在我的脚本中,我调用了一个很长的函数。我想在函数中包含与降价混合的部分代码。我不知道如何将函数拆分为单独的代码块和降价。
在下面的示例中,我有一个函数 getres()。我想在“我想要的”标题下方显示此功能。有办法吗?
---
title: "Example"
output: html_document
---
## What I have now:
```{r desiref}
getRes <- function(){
# Here I'm calculating 1+1:
res<- 1+1
# Here I'm multiplying the resuls by two:
res<- res*2
return(res)
}
res<-getRes()
```
The results is: `r res`
## What I want:
Here I'm calculating 1+1:
```{r ex1}
res <- 1+1
```
Here I'm multiplying the resuls by two:
```{r ex2}
res<- res*2
```
The results is: `r res`
这给出了降价:
我现在拥有的:
getRes <- function(){
# Here I'm calculating 1+1:
res<- 1+1
# Here I'm multiplying the resuls by two:
res<- res*2
return(res)
}
res<-getRes()
结果是:r res
我想要的是:
这里我计算 1+1:
res <- 1+1
在这里,我将结果乘以 2:
res<- res*2
结果是:r res
解决方案
这实际上可能已经在这个问题中得到了解决: 如何在 Rmarkdown 中解释一个复杂的函数?
答案是(我添加了一个额外的参数来检查函数是否正常工作):
---
title: "Example"
output: html_document
---
## Old function:
```{r desiref, echo=FALSE}
getRes <- function(){
# Here I'm calculating 1+1:
res<- 1+1
# Here I'm multiplying the resuls by two:
res<- res*2
return(res)
}
res<-getRes()
```
## Answer :
Here I'm calculating 1+1:
```{r Xsquare1, eval=F}
res<- 1+x
```
Here I'm multiplying the resuls by two:
```{r Xsquare2, eval=F}
res<- res*2
```
```{r complicated, eval=T, echo=FALSE}
complicated = function(x) {
<<Xsquare1>>
<<Xsquare2>>
}
res=complicated(5)
```
The results is: `r res`
## Old requirement:
Here I'm calculating 1+1:
```{r ex1}
res <- 1+1
```
Here I'm multiplying the resuls by two:
```{r ex2}
res<- res*2
```
The results is: `r res`
推荐阅读
- c++ - 自动格式化程序将 >> 更改为 >>
- c++ - 以非特权用户身份查询 NTFS 特殊文件的元数据?
- javascript - 如何创建静态工作表 XLSX
- c# - base 64编码和解码的问题
- php - 无法在服务器端刷新 Google Calendar API 的访问令牌
- ruby-on-rails - Rails select_tag 使用范围进行简单过滤
- json - 在 iex 中运行 elixir 毒药命令
- javascript - Firefox 本地存储值有时会在新选项卡中丢失
- ios - 在 swift 中使用 xcode 10 未显示初始屏幕徽标图像
- protocol-buffers - 如何根据消息内容拦截和转发 GRPC 调用