r - R - Matching strings to dictionary and replacing
问题描述
I making bar charts in R and want to change the x-axis strings using a dictionary that I have defined containing more readable names. Here is an example of the code.
mydata
name value
<chr> <dbl>
1 jd 20
2 mk 30
3 js 40
readable_strings <- c("John Smith" = "js", "Jane Do" = "jd", "Mike Tyson" = "mt")
ggplot(mydata, aes(x = name, y=value)) + geom_bar(stat="identity")
I would like the readable names to be displayed along the x-axis. What is the best way for me to do this?
解决方案
你可以做:
# reverse the vector
convert_vec <- names(readable_strings)
names(convert_vec) <- readable_strings
# replace the values and plot
mydata$name <- sapply(mydata$name, function(x) convert_vec[[x]])
ggplot(mydata, aes(x = name, y=values)) + geom_bar(stat="identity")
推荐阅读
- python - 带有文件名的类型错误
- casting - 天花板操作给出了错误的答案
- json - 根据过滤器将两个 json 有效负载聚合为一个
- javascript - 改进了在 Promise 中处理回调的方法
- windows - 我的应用程序有什么权限,在启动时启动?(HKLM\...\运行)
- floating-point - 理解 IEEE 中的指数 00000000 和 11111111
- javascript - 通过 JavaScript/CSS 快速播放图像?
- regex - 如何在notepadpp中使用正则表达式反向引用进行计算?
- javascript - 如何从角度的环回关系中过滤?
- python - Postgres 和 Docker 在文件更改时重新部署