用R中的小数转换所有%

sea*_*ele 2 replace r character percentage dataframe

我有一个大数据框,其中百分比写为 10% 而不是 0.1。并非所有列都是百分比,但相当多的是。

有没有一种优雅的方法将所有 % 转换为小数?我特别关心百分比可能大于 100% 的情况,并且该规则可以应用于整个 tibble,而不必弄清楚要定位哪些列。

示例如果不清楚......这个:

tibble(cola = c("hello", "good bye", "hi there"), colb = c("10%", "20%", "100%"), colc = c(53, 67, 89),cold = c("10%", "200%", "50%") )
Run Code Online (Sandbox Code Playgroud)

对此:

tibble(cola = c("hello", "good bye", "hi there"), colb = c(.10, .20, 1.0), colc = c(53, 67, 89),cold = c(.10, 2.0, .5) )
Run Code Online (Sandbox Code Playgroud)

谢谢。

Rui*_*das 5

编写一个辅助函数并mutate_if基于其值。

is.percentage <- function(x) any(grepl("%$", x))

df1 %>%
  mutate_if(is.percentage, ~as.numeric(sub("%", "", .))/100)
## A tibble: 3 x 4
#  cola      colb  colc  cold
#  <chr>    <dbl> <dbl> <dbl>
#1 hello      0.1    53   0.1
#2 good bye   0.2    67   2  
#3 hi there   1      89   0.5
Run Code Online (Sandbox Code Playgroud)