首页 > 解决方案 > 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?

标签: rggplot2replacematch

解决方案


你可以做:

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

推荐阅读