Currently I'm working on a dashboard in R using flexdashboard. I'm using different Excel-/CSV-datasources to generate an html-output. It's my goal to display (as one part of the dashboard) an Excel-Datasheet in a page of the dashboard. The dataframe imported from the Excel-data looks (simplified) as follows:
text_col <- c("A", "B", "C", "D")
jan_col <- c(0.2, 0.3, 12, 0.4)
feb_col <- c(0.1,0.2, 12.5, 0.8)
dt <- data.frame("TEXT" = text_col, "JAN" = jan_col, "FEB" = feb_col)
Now I want to have an output in my dashboard, where the numbers < 1 are formatted as percentages. It is important, that the numbers > 1 (e.g. 12 and 12.5) as well as the text (obviously) are not formatted as percentages.
So far I've tried to select a subset and overwrite this subset using the percent-function in R. This works for the actual subset but does not update the original table:
library(dplyr)
dt[c(1:2,4),c(2:3)] <- dt[c(1:2,4),c(2:3)] %>% mutate_each(list(percent))
Is there any way to just mutate the cells I want to have formatted in percentages?
I thank you for your help in advance!
You could use ifelse
to test for conditions.
library(dplyr)
dt %>% mutate_at(-1, ~ifelse(. < 1, scales::percent(.), .))
Or if you just want to add '%'
symbol to numbers
dt %>% mutate_at(-1, ~ifelse(. < 1, paste0(., '%'), .))
You can also do this in base R :
dt[-1] <- lapply(dt[-1], function(x) ifelse(x < 1, paste0(x, '%'), x))