我如何说服 fct_infreq 我正在使用数值向量?

How do I convince fct_infreq I'm working with a numerical vector?

我花了很多精力创建一个新变量,andel,我想使用 ggplot2 按频率顺序可视化它。

我写:

ggplot(df,aes())+geom_col(mapping=aes(x=NYA_REGION, y=fct_infreq(andel)))

我收到一条错误消息,声称:

Error: `f` must be a factor (or character vector or numeric vector).

我已经使用了所有诊断工具作为我的处置,"andel" 似乎是一个数字向量。到底是什么问题,我该如何解决?

重复:

structure(list(NYA_REGION = structure(2:11, .Label = c("UTANFÖR SVERIGE", 
"ÖVRIGA LANDET", "STORGÖTEBORG", "oklart", "SÖDRA BOHUSLÄN", 
"VÄSTERGÖTLAND", "VÄNERSBORG", "UDDEVALLA", "TROLLHÄTTAN", "DALSLAND", 
"NORRA BOHUSLÄN"), class = c("ordered", "factor")), totstatus_tri = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("pågående studier", 
"tidigt avbrott eller återbud", "sent avbrott"), class = c("ordered", 
"factor")), ongoing = c(10L, 107L, 128L, 32L, 36L, 14L, 41L, 
63L, 8L, 15L), antal = c(10L, 107L, 128L, 32L, 36L, 14L, 41L, 
63L, 8L, 15L), andel = c(0.144927536231884, 0.36518771331058, 
0.457142857142857, 0.450704225352113, 0.48, 0.4, 0.577464788732394, 
0.456521739130435, 0.727272727272727, 0.681818181818182)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), groups = structure(list(
    NYA_REGION = structure(2:11, .Label = c("UTANFÖR SVERIGE", 
    "ÖVRIGA LANDET", "STORGÖTEBORG", "oklart", "SÖDRA BOHUSLÄN", 
    "VÄSTERGÖTLAND", "VÄNERSBORG", "UDDEVALLA", "TROLLHÄTTAN", 
    "DALSLAND", "NORRA BOHUSLÄN"), class = c("ordered", "factor"
    )), .rows = list(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

根据 documentation fct_infreq() 适用于因数,而不是数字。不过没关系,您可以使用 as.factor

进行转换
ggplot(df, aes()) + 
  geom_col(aes(x = NYA_REGION, y = fct_infreq(as.factor(andel))))

就是说,在您的示例中,andel

的每个值只出现一次

此外,当我 运行 你的例子时,我得到了一个稍微不同的错误:

Error: f must be a factor (or character vector).

这是我的会话信息:

R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)
other attached packages: 
forcats_0.5.0   stringr_1.4.0   dplyr_0.8.3     purrr_0.3.3     readr_1.3.1    
tidyr_1.0.2     tibble_2.1.3    ggplot2_3.3.0   tidyverse_1.3.0