Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R convert numeric to percentage the 'tidyverse way" using percent_format

Tags:

r

I have a column of numbers that I want to change from a count to a percentage.

This code works:

    df <- df %>% 
  select(casualty_veh_ref, JourneyPurpose ) %>%
  group_by(JourneyPurpose) %>%
  summarise(Number=n()) %>%
mutate(Percentage=Number/sum(Number)*100)

df$Percentage <- paste(round(df$Percentage), "%", sep="")

But if I try to keep the piping using percent_format from the scales package:

df <- df %>% 
  select(casualty_veh_ref, JourneyPurpose ) %>%
  group_by(JourneyPurpose) %>%
  summarise(Number=n()) %>%
mutate(Percentage=Number/sum(Number))  %>% 
percent_format(Percentage, suffix = "%")

I receive the error message

Error in force_all(accuracy, scale, prefix, suffix, big.mark, decimal.mark,  : 
  object 'Percentage' not found

I don't understand why the object is not found

like image 304
user3387656 Avatar asked Jan 02 '23 09:01

user3387656


1 Answers

Try this: I've used iris for representation.

library(dplyr)
iris %>% 
  slice(1:4) %>% 
  mutate(Test=Sepal.Length/45,Test=scales::percent(Test)) 

Result:

Sepal.Length Sepal.Width Petal.Length Petal.Width Species   Test
1          5.1         3.5          1.4         0.2  setosa 11.33%
2          4.9         3.0          1.4         0.2  setosa 10.89%
3          4.7         3.2          1.3         0.2  setosa 10.44%
4          4.6         3.1          1.5         0.2  setosa 10.22%
like image 188
NelsonGon Avatar answered Jan 05 '23 02:01

NelsonGon