将值格式化为百分比,保持数字

Format values as percent keeping them numeric

我想将值格式化为百分比,它还附加了 % 单位。我正在尝试以下步骤:

df<-data.frame(x=c("A","B","C","D","E"),Y=c(23,24,25,34,32))
df$Z<-sprintf("%.1f%%",df$Y)

但是这样新列z就是字符。稍后我需要在 using library(DT) 中提供一个带有数据条的 DT table。像这样:

datatable(df)%>% formatStyle(c(2:3), background = styleColorBar(c(0,100), 'lightblue'),
                              backgroundSize = '98% 88%',
                              backgroundRepeat = 'no-repeat',
                              backgroundPosition = 'center')

由于 Z 列现在是字符列,因此无法在 Z 上创建条形图。 我需要一些解决方案,可以将数字格式化为百分比(将 % 显示为后缀)但仍将它们保持为 numeric ,以便可以创建数据栏。只能在数值上创建数据条。

您可以使用 formatPercentage

df<-data.frame(x=c("A","B","C","D","E"),Y=c(23,24,25,34,32))
df$Z<- df$Y/100

datatable(df) %>%
    formatPercentage(3) %>% 
    formatStyle(3, background = styleColorBar(c(0,1), 'lightblue'),
                         backgroundSize = '98% 88%',
                         backgroundRepeat = 'no-repeat',
                         backgroundPosition = 'center')