r - 如何说服 fct_infreq 我正在使用数值向量?
问题描述
我付出了很多努力来创建一个新变量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))
解决方案
根据文档 fct_infreq()
适用于因素,而不是数字。没关系,你可以转换为as.factor
ggplot(df, aes()) +
geom_col(aes(x = NYA_REGION, y = fct_infreq(as.factor(andel))))
也就是说,在您的示例中,每个值仅出现一次andel
此外,当我运行您的示例时,我得到一个稍微不同的错误:
错误:
f
必须是一个因子(或字符向量)。
这是我的会话信息:
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
推荐阅读
- docker - 无法访问内部网络中 vm 上运行的容器 url
- c# - 如何更改将在任务栏上显示的图标
- java - 即使在 setText 之后芯片文本也是空的
- c# - 将行为添加到相互调用的重写重载
- apache-flink - 生成“心跳”类型的事件来推动事件时间
- r - 如何将 stat_poly_eq 标签放在构面图之外?
- python - ImportError:无法从“importlib”导入名称“元数据”
- gdb - 在 QNX gdb 上运行可执行文件而不重新上传它
- vue.js - Nuxt.js:如何从布局中引用页面数据?(例如,填充 og:title 标签)
- java - 以一个属性文件为前缀的批量弹簧属性值