Home > Mobile >  Source .R file to Rmarkdown does not work with German Umlaut
Source .R file to Rmarkdown does not work with German Umlaut

Time:06-26

In order to slim down my Rmarkdown code I would like to write some code in R files and then source to Rmarkdown:

my_script_01.R

library(tidyverse)
df1 <- tribble(
  ~id, ~col1,
  1, "Äb",
  2, "Ab",
  3, "ÖB",
  4, "OB"
)
df1
df2 <- tibble(id = c(1:4),
              tester = c("umlaut", "no_umlaut", "umlaut", "no_umlaut"))
df3 <- left_join(df1, df2, by="id")

In principle it works fine:

  1. Only if I source content with german Umlaute (ä,ü,ö etc..) sourcing does not work properly, it gives strange letters (blue rectangle, code 1).

  2. If I put the code into the r markdown chunk then everything works perfect (red circle, code 2)

Rmd Code 1:

---
title: "test"
author: "Me"
date: '2022-06-25'
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
source("my_script_01.R")
```


```{r}

df3 %>% 
  count(col1) %>%
  ggplot(aes(x=col1, y=n))  
  geom_col() 
  theme_minimal(base_size = 26) 
```

enter image description here

Rmd Code 2:

---
title: "test"
author: "Me"
date: '2022-06-25'
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
source("my_script_01.R")
```


```{r}
df1 <- tribble(
  ~id, ~col1,
  1, "Äb",
  2, "Ab",
  3, "ÖB",
  4, "OB"
)
df2 <- tibble(id = c(1:4),
              tester = c("umlaut", "no_umlaut", "umlaut", "no_umlaut"))
df3 <- left_join(df1, df2, by="id")

df3 %>% 
  count(col1) %>%
  ggplot(aes(x=col1, y=n))  
  geom_col() 
  theme_minimal(base_size = 26) 
```

enter image description here

My default text-encoding is UTF-8. I would like to know why this behaviour occurs and if it is possible to source with german umlaute.

I look around for example here or here but could not find a solution.

CodePudding user response:

Specifying the encoding of the sourced file should help:

source("my_script_01.R", encoding="UTF-8")
  • Related