R使用percent_format以“ tidyverse方式”将数字转换为百分比

时间:2019-01-25 15:27:09

标签: r

我有一列数字,我希望将其从计数更改为百分比。

此代码有效:

    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="")

但是,如果我尝试使用scales软件包中的percent_format保留管道,则

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

我收到错误消息

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

我不明白为什么找不到该对象

1 个答案:

答案 0 :(得分:1)

尝试一下:我用虹膜来表示。

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

结果:

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%