0

My problem relates to translation of accented characters in R/Shiny - I tried to employ the solution discussed here but ran into a frustrating exception:

Within RStudio; if I highlight all lines of the code below and then press Ctrl+Enter (Run-Selected-Lines) I get the expected output of "ooo".

However if I press 'Run App' (as part of a project) I instead get "ǒoo" - i.e. the first character doesn't get mapped.

library(shiny)
ui <- fluidPage()

server <- function(input, output) {
  charactermap = list('ǒ'='o', 'ô'='o', 'ø'='o')

  removeaccents <- function(x) {
    corrected <- chartr(paste(names(charactermap), collapse=''),
                    paste(charactermap, collapse=''),
                    x)
    return(corrected)
 }

 print(removeaccents("ǒôø")) 
}

# Run the application 
shinyApp(ui = ui, server = server)

This seems to happen with only a small number of characters I am interested in - any ideas why this may be happening and how to fix it please???

SeGa
  • 9,454
  • 3
  • 31
  • 70
s1jinglis
  • 1
  • 1
  • 1
    Have you tried adding an encoding argument? This for example: `options(encoding = 'UTF-8')` – SeGa May 16 '18 at 14:22
  • Your example works fine for me. `getOption("encoding")` returns `native.enc` & `Sys.getlocale("LC_CTYPE")` returns `fr_FR.UTF-8` – qfazille May 16 '18 at 15:54
  • Thanks SeGa: Do you mean to add this globally - i.e. adding above my 'ui' statement? I have tried to manipulate the encoding of my list and input string throughout my script without any success. I have no prior experience of character encoding unfortunately. – s1jinglis May 16 '18 at 17:10
  • Thanks @SeGa; @qfazille. `Sys.getlocale` returns `English_United Kingdom.1252` & `getOption("encoding")` returned `native.enc` before I changed to UTF-8 – s1jinglis May 16 '18 at 17:29
  • Yes you can define it globally. I would actually create a global.R file, where you put the `removeaccents`-function and the `charactermap`, as they dont need to be in the server-function. And there you would also put the encoding-option. – SeGa May 16 '18 at 17:34
  • Appreciate that @SeGa; good point. Unfortunately that doesn't solve the underlying problem however. – s1jinglis May 16 '18 at 18:38
  • After reading the shiny-tutorials [link](https://shiny.rstudio.com/articles/unicode.html), setting the encoding globally is considered bad practice. – SeGa May 16 '18 at 20:40
  • 1
    I found that using `iconv` to explicitly convert my string to UTF-8 I received some fresh errors but these were resolved when I switched to using `gsubfn` from `chartr` above. As suggested I have also transferred my function in a separate script file which I load using the `source()` function. Thanks to @SeGa in particular for all tips and comments. – s1jinglis May 18 '18 at 15:33

0 Answers0