代码之家  ›  专栏  ›  技术社区  ›  Luis

管理R和ggplot中字符串的错误顺序。X1,X10,X12:我如何确保一个带有数字的字符串以正确的数字顺序排列?

  •  0
  • Luis  · 技术社区  · 2 年前

    每当我想绘制或列出一个包含数字的字符串时,R(和python)都会列出诸如“x1,x10,x11,x13,(等)x2,x3,x4”之类的值

    image

    我试图用 gtools::mixedsort(variable) 但由于某种超出我知识和耐心的原因,它不起作用。

    有人能告诉我如何解决这个问题吗?代码如下:

    library(tidyverse)
    df = data.frame(data.frame(x = 1:3))
    for (i in 1:15) {
      df[ , paste0("asq_", i)]   <- c(0,5,10)
    }
    
    df %>% 
      pivot_longer(-x,names_to = "asq_item", values_to = "response")%>% 
      group_by(asq_item, response) %>%
      summarise(count = n(), .groups = 'drop') %>%
      group_by(asq_item) %>%
      mutate(proportion = count / sum(count)) %>%
      ggplot(., aes(x = asq_item, y = proportion, fill = factor(response)))+
      geom_bar(stat = "identity",  position=position_dodge2(width = 0.9, preserve = "single")) +
      labs(title = "Prevalence of Each Category Within Each ASQ Item",
           x = "ASQ Item",
           y = "Count",
           fill = "Response") +
      theme_bw() 
    

    创建于2024年7月23日 reprex v2.1.0

    1 回复  |  直到 2 年前
        1
  •  2
  •   Edward    2 年前

    好吧,你走对了路,但你没有显示你尝试的代码。您可以通过将变量转换为因子来实现这一点,并将级别指定为唯一 已排序 价值观。

    library(gtools)
    df %>% 
      pivot_longer(-x, names_to = "asq_item", values_to = "response") %>% 
      mutate(asq_item=factor(asq_item, levels=mixedsort(unique(asq_item)))) %>%
      group_by(asq_item, response) %>%
    ...
    

    给你 enter image description here