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

旋转数据但保持数据在R中对齐?

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

    我在R中有一个大数据帧,它看起来如下所示:

    Age   Gene1   Gene2   Gene3 
    33     0       1       1
    57     1       0       1
    90     1       1       1
    

    我试图把这些数据绘制在一个条形图上,用基因绘制的频率来表示年龄。当我尝试使用以下工具透视数据时:

    pivoted_df <- df %>%
    pivot_longer(AGE, names_to="genes", values_to="count")
    

    Age  Gene  Count
    33   Gene1   0
    33   Gene2   1
    33   Gene3   1  
    57   Gene1   1
    57   Gene2   0
    57   Gene3   1
    90   Gene1   1
    90   Gene2   1
    90   Gene3   1
    

    有没有一种方法可以让我在不重复年龄的情况下透视数据?一、 E仍然保留基因和计数列,但将多个值从该值分配给一个年龄?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Quinten    2 年前

    也许您希望这样,您可以使用 melt as.factor 要按如下方式绘制堆叠条形图:

    df <- read.table(text = "Age   Gene1   Gene2   Gene3 
    33     0       1       1
    57     1       0       1
    90     1       1       1", header = TRUE)
    
    library(dplyr)
    library(ggplot2)
    library(reshape)
    df %>%
      melt(id.vars = "Age") %>%
      mutate(Age = as.factor(Age)) %>%
      ggplot(aes(x = Age, y = value, fill = variable)) +
      geom_col() +
      labs(fill = "gene", y = "count") +
      theme_bw()
    

    于2022年7月26日由 reprex package