0

I got a little issue with recoding some values in shiny. It seems that my values are integrated as factors, but I would like to use them as numeric variables.

I try to explain. Here's a minimal example:

datensatz_patient <- reactive({datensatz <- input$datensatz
                               infile    <- read.table(datensatz$datapath, header=TRUE, strip.white = TRUE, stringsAsFactors = FALSE, sep=";",dec=",", na = -77)

BSI_dat           <- reactive(subset(datensatz_patient(), select = c(Base_BSI_v1:Base_BSI_v53))

BSI.sub_soma      <- reactive(subset(BSI_dat(), select = c(2, 7, 23, 29, 30, 33, 37))) 

BSI.soma.SW       <- reactive(apply(BSI.sub_soma(),1, mean, as.numeric = TRUE, na.rm = TRUE))

BSI.soma.T_m      <- reactive(recode(BSI.soma.SW(), "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112"))


output$test8.1 <- renderTable(BSI.soma.SW())
output$test8.2 <- renderTable(BSI.soma.T_m())

My problem is, that the recoding of BSI.soma.SW doesn't work properly. With integers (1 or 2) BSI.soma.T_m gets the new value (1 = 60 or 2 = 80). With decimal numbers it doesn't work. Decimal numbers aren't recoded. where's my mistake? What should I do?

Thank you for your help

divibisan
  • 11,659
  • 11
  • 40
  • 58
lderlu
  • 11
  • 4

1 Answers1

0

I think your format for the replacements in your recode expression is off. It's hard to tell precisely, since you don't include a sample of your data, but I generated a vector of numbers that should suffice:

Using the recode expression in your example with a vector of numbers does not give the right answer:

recode(c(0,1,1,.17,2,3.71), "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112")
[1] NA                                                        
[2] "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112"
[3] "0 = 41; 0.17 = 50; 1 = 60;  1.5 = 70; 2 = 80; 3.71 = 112"
[4] NA                                                        
[5] NA                                                        
[6] NA                                                        
Warning message:
Unreplaced values treated as NA as .x is not compatible. Please specify replacements exhaustively or supply .default

If we fix Replacements to be multiple comma separated, named vectors (with an L to make them explicit integers. See this answer: What's the difference between `1L` and `1`?), we get the correct result:

recode(c(0,1,1,.17,2,3.71), '0' = 41L, '0.17' = 50L, '1' = 60L,  '1.5' = 70L, '2' = 80L, '3.71' = 112L)
[1]  41  60  60  50  80 112
divibisan
  • 11,659
  • 11
  • 40
  • 58