Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert columns i to j to percentage

Tags:

r

dplyr

Suppose I have the following data:

df1 <- data.frame(name=c("A1","A1","B1","B1"),
                  somevariable=c(0.134,0.5479,0.369,NA),
                  othervariable=c(0.534, NA, 0.369, 0.3333))

In this example, I want to convert columns 2 and 3 to percentages (with one decimal point). I can do it with this code:

library(scales)
df1 %>%
  mutate(somevariable=try(percent(somevariable),silent = T),
         othervariable=try(percent(othervariable),silent = T))

But I'm hoping there is a better way, particularly for the case where I have many columns instead of just 2.

I tried mutate_each but I'm doing something wrong...

df1 %>%
  mutate_each(funs = try(percent(),silent = T), -name)

Thanks!

like image 654
Ignacio Avatar asked Dec 10 '25 20:12

Ignacio


1 Answers

Here's an alternative approach using custom function. This function will only modify numeric vectors, so no need to worry about try or removing non-numeric columns. It will also handle NAs by defult

myfun <- function(x) {
  if(is.numeric(x)){ 
    ifelse(is.na(x), x, paste0(round(x*100L, 1), "%")) 
  } else x 
}

df1 %>% mutate_each(funs(myfun))
#   name somevariable othervariable
# 1   A1        13.4%         53.4%
# 2   A1        54.8%          <NA>
# 3   B1        36.9%         36.9%
# 4   B1         <NA>         33.3%
like image 143
David Arenburg Avatar answered Dec 13 '25 11:12

David Arenburg