I am testing to use parameterized RMarkdown, using c as a parameter. I am using Knit with parameters
choosing a
or b
, or nothing which by default chooses a
.
I expect to obtain 2 or 5 as the mean but I always obtain 3.5 which is the global mean.
What am I doing wrong here?
---
title: "Parameterized RMarkdown"
output:
html_document: default
params:
c: "a"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(knitr)
```
```{r mean, echo=FALSE}
df <- tibble(c = c("a", "a", "a", "b", "b", "b"),
x = c(1, 2, 3, 4, 5, 6))
mean(df$x)
```
We can add a filter
on the extracted 'params' and get the mean
of the column 'x'
library(dplyr)
df %>%
filter(c == params$c) %>%
summarise(x = mean(x, na.rm = TRUE))
Or use base R
to do this
with(df, mean(x[c == params$c], na.rm = TRUE))