【问题标题】:How to convert wide format to long format with an added factor name如何使用添加的因子名称将宽格式转换为长格式
【发布时间】:2021-04-29 16:40:15
【问题描述】:

我想将宽格式数据(样本名称放在列名中)转换为长格式(其中为该样本名称添加了一个列)。

查看示例:

df <-data.frame(Assay=c("alpha","beta","theta"),
                One_mean    =c(3,4,5), 
                Two_mean    =c(6,7,8), 
                Three_mean  =c(8,8,8),
                One_plus    =c(1.3,1.4,1.5), 
                Two_plus    =c(1.6,1.7,1.8), 
                Three_plus  =c(1.8,1.8,1.8),
                One_minus   =c(.3,.4,.5), 
                Two_minus   =c(.6,.7,.8), 
                Three_minus =c(.8,.8,.8))

输出:

output_df <- data.frame(Assay=c("alpha","beta","theta",
                                "alpha","beta","theta",
                                "alpha","beta","theta"), 
                        Sample= c("One", "Two", "Three",
                                  "One", "Two", "Three",
                                  "One", "Two", "Three"),
                        mean = c(3,4,5,
                                 6,7,8,
                                 8,8,8),
                        plus = c(1.3,1.4,1.5,
                                 1.6,1.7,1.8,
                                 1.8,1.8,1.8),
                        minus = c(.3,.4,.5,
                                  .6,.7,.8,
                                  .8,.8,.8))

谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用pivot_longer

    library(tidyr)
    pivot_longer(df, cols = -Assay, names_to = c("Sample", ".value"), names_sep = '_')
    

    -输出

    # A tibble: 9 x 5
    #  Assay Sample  mean  plus minus
    #  <chr> <chr>  <dbl> <dbl> <dbl>
    #1 alpha One        3   1.3   0.3
    #2 alpha Two        6   1.6   0.6
    #3 alpha Three      8   1.8   0.8
    #4 beta  One        4   1.4   0.4
    #5 beta  Two        7   1.7   0.7
    #6 beta  Three      8   1.8   0.8
    #7 theta One        5   1.5   0.5
    #8 theta Two        8   1.8   0.8
    #9 theta Three      8   1.8   0.8
    

    【讨论】:

      【解决方案2】:

      使用reshpae 的基本 R 选项

      reshape(
        setNames(df, gsub("(\\w+)_(\\w+)", "\\2.\\1", names(df))),
        direction = "long",
        idvar = "Assay",
        varying = -1
      )
      

      给予

                  Assay  time mean plus minus
      alpha.One   alpha   One    3  1.3   0.3
      beta.One     beta   One    4  1.4   0.4
      theta.One   theta   One    5  1.5   0.5
      alpha.Two   alpha   Two    6  1.6   0.6
      beta.Two     beta   Two    7  1.7   0.7
      theta.Two   theta   Two    8  1.8   0.8
      alpha.Three alpha Three    8  1.8   0.8
      beta.Three   beta Three    8  1.8   0.8
      theta.Three theta Three    8  1.8   0.8
      

      【讨论】:

        猜你喜欢
        • 2015-07-18
        • 2016-03-28
        • 1970-01-01
        • 1970-01-01
        • 2018-01-31
        • 2021-07-20
        • 1970-01-01
        相关资源
        最近更新 更多