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!
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%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With