【问题标题】:transform dataset to tidy format combining column and row in R将数据集转换为在 R 中结合列和行的整洁格式
【发布时间】:2020-01-30 15:23:50
【问题描述】:

我的数据集结构有些不妥:

Species    site  2001  2002  2003 
a          1      0     1    4
a          2      1     1    0
a          3      5     5    5
b          1      3     0    4
b          2      1     1    1
b          3      4     5    5

在尝试使用 R 获得正确格式数小时后,我在 Excel 中进行了操作,并将其转换为以下格式。

ID       a   b
1_2001   0   3
1_2002   1   0
1_2003   4   4
2_2001   1   1
2_2002   1   1
2_2003   0   1
3_2001   5   4
3_2002   5   5
3_2004   5   5

原始数据集相当大,我不能让它休息,因为我不知道如何在 R 中快速做到这一点。 有人可以向我解释如何在 R 中完成这种转换吗?

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    使用tidyrdplyr,你可以先将我们的年份列重新整形为更长的格式,然后使用pivot_wider创建“a”和“b”列,组装“站点”和“ID”最后只保留所需的列:

    library(tidyr)
    library(dplyr)
    df %>% pivot_longer(.,-c(Species, site), names_to = "ID", values_to = "val") %>%
      pivot_wider(.,names_from = Species, values_from = val) %>%
      rowwise() %>%
      mutate(ID = paste(site,ID, sep = "_")) %>%
      select(ID, a, b)
    
    Source: local data frame [9 x 3]
    Groups: <by row>
    
    # A tibble: 9 x 3
      ID         a     b
      <chr>  <int> <int>
    1 1_2001     0     3
    2 1_2002     1     0
    3 1_2003     4     4
    4 2_2001     1     1
    5 2_2002     1     1
    6 2_2003     0     1
    7 3_2001     5     4
    8 3_2002     5     5
    9 3_2003     5     5
    

    数据

    structure(list(Species = c("a", "a", "a", "b", "b", "b"), site = c(1L, 
    2L, 3L, 1L, 2L, 3L), `2001` = c(0L, 1L, 5L, 3L, 1L, 4L), `2002` = c(1L, 
    1L, 5L, 0L, 1L, 5L), `2003` = c(4L, 0L, 5L, 4L, 1L, 5L)), row.names = c(NA, 
    -6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x56276b4f1350>)
    

    【讨论】:

      【解决方案2】:

      这里是gatherspread 的另一个解决方案,来自tidyr-package

      tibble::tibble(Species = c("a", "a", "a", "b", "b", "b"), 
                     site = c(1L, 2L, 3L, 1L, 2L, 3L), 
                     `2001` = c(0L, 1L, 5L, 3L, 1L, 4L), 
                     `2002` = c(1L, 1L, 5L, 0L, 1L, 5L), 
                     `2003` = c(4L, 0L, 5L, 4L, 1L, 5L)) %>% 
        tidyr::gather(-Species, -site, key = "key", value = "value") %>% 
        tidyr::spread(key = "Species", value = "value")
      

      输出:

      # A tibble: 9 x 4
         site key       a     b
        <int> <chr> <int> <int>
      1     1 2001      0     3
      2     1 2002      1     0
      3     1 2003      4     4
      4     2 2001      1     1
      5     2 2002      1     1
      6     2 2003      0     1
      7     3 2001      5     4
      8     3 2002      5     5
      9     3 2003      5     5
      

      【讨论】:

        猜你喜欢
        • 2021-11-30
        • 2020-02-18
        • 2022-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        • 2020-02-17
        • 1970-01-01
        相关资源
        最近更新 更多