【问题标题】:R - Matching strings to dictionary and replacingR - 将字符串匹配到字典并替换
【发布时间】:2018-12-08 07:45:03
【问题描述】:

我在 R 中制作条形图,并希望使用我定义的包含更易读名称的字典来更改 x 轴字符串。下面是代码示例。

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

我希望沿 x 轴显示可读的名称。我这样做的最佳方法是什么?

【问题讨论】:

    标签: r ggplot2 replace match


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 2019-10-06
      • 2023-02-16
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 2016-09-14
      相关资源
      最近更新 更多