【问题标题】:Reshape dataset in R_ move row to columnR中的重塑数据集将行移动到列
【发布时间】:2022-01-16 23:04:30
【问题描述】:

我有一个格式如下的数据集:

enter image description here

structure(list(SNPID = c("SNP_A-1780520", "SNP_A-1780618", "SNP_A-1780632"
), no.1 = c("BB", "AB", "AA"), no.2 = c("BB", "AB", "AA"), no.3 = c("BB", 
"AB", "AB")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"))`  

我想重塑数据集,将每个 SNPID 作为一列,将每个“no”作为一行。

我尝试了不同的 R 包,但未能成功管理这个简单的任务。我很感激任何帮助。我想要这样的东西: enter image description here

【问题讨论】:

  • 嗨,米拉德。请提供一些可重现的数据(例如使用函数dput())。谢谢
  • 谢谢,完成@Marco_CH
  • 这样的东西使用(library(tidyr))? df %>% pivot_longer(-SNPID) %>% pivot_wider(names_from = SNPID, values_from = value)

标签: r dplyr reshape


【解决方案1】:

data.table::transpose 就是这种情况

data.table::transpose(df1, make.names = "SNPID",  keep.names = "name")
  name SNP_A-1780520 SNP_A-1780618 SNP_A-1780632
1 no.1            BB            AB            AA
2 no.2            BB            AB            AA
3 no.3            BB            AB            AB

【讨论】:

    【解决方案2】:

    Base R 并作为 oneliner:

    df = structure(list(SNPID = c("SNP_A-1780520", "SNP_A-1780618", "SNP_A-1780632" ), no.1 = c("BB", "AB", "AA"), no.2 = c("BB", "AB", "AA"), no.3 = c("BB",  "AB", "AB")), row.names = c(NA, -3L), class = c("tbl_df", "tbl",  "data.frame"))
    
    df_new = as.data.frame(t(df))
    

    输出:

    df_new
                     V1            V2            V3
    SNPID SNP_A-1780520 SNP_A-1780618 SNP_A-1780632
    no.1             BB            AB            AA
    no.2             BB            AB            AA
    no.3             BB            AB            AB
    

    【讨论】:

      【解决方案3】:

      使用tidyr()重塑数据的示例

      library (tidyr)
      
      df %>% 
        pivot_longer(-SNPID) %>% 
        pivot_wider(names_from = SNPID, values_from = value)
      
         name  `SNP_A-1780520` `SNP_A-1780618` `SNP_A-1780632` `SNP_A-1780654`
        <chr> <chr>           <chr>           <chr>           <chr>          
      1 no.1  BB              AB              AA              AA             
      2 no.2  BB              AB              AA              AA             
      3 no.3  BB              AB              AA              AA   
      

      【讨论】:

        猜你喜欢
        • 2020-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-11
        • 2017-12-04
        • 2015-09-30
        • 1970-01-01
        相关资源
        最近更新 更多