【问题标题】:Summarizing the data in a data table汇总数据表中的数据
【发布时间】:2020-04-16 16:50:12
【问题描述】:

您好,我有以下输入。

+------+----+----+
| CODE | R1 | R2 |
+------+----+----+
| A    |  0 |  1 |
| B    |  1 |  1 |
| C    |  0 |  0 |
+------+----+----+

我需要如下输出。

+------+------+-------+
| CODE | CODE | VALUE |
+------+------+-------+
| A    | R1   |     0 |
| A    | R2   |     1 |
| B    | R1   |     1 |
| B    | R2   |     1 |
| C    | R1   |     0 |
| C    | R2   |     0 |
+------+------+-------+

请注意R1R2等区域,实际数据中有很多R3R4R5等区域。为简单起见,我只放了R1R2

提前感谢您的帮助!

【问题讨论】:

  • 不知道为什么它没有以表格格式出现
  • 嗨@avinash0513,一旦我的编辑被接受,请检查格式,如果您有更多问题回来,您可以遵循:)
  • 这将在以后的问题中帮助您:How to make a great R reproducible example,修改您的问题,从您的数据中提取更小的样本(检查?dput())。

标签: r dataframe formatting data-manipulation


【解决方案1】:

使用data.table,我们可以使用melt

library(data.table)
melt(setDT(df1), id.var = 'CODE')

【讨论】:

    【解决方案2】:

    将数据从宽格式转换为长格式的非常经典的场景。并直接从 使用pivot-longer

    df <- read.table(stringsAsFactors = F, header = T, text = "
               CODE R1  R2
               A    0   1
               B    1   1
               C    0   0");
    
    dfTarget <- read.table(stringsAsFactors = F, header = T, text = "
     CODE  CODE  VALUE 
     A     R1        0 
     A     R2        1 
     B     R1        1 
     B     R2        1 
     C     R1        0 
     C     R2        0");
    
    

    现在,你想要的代码:

    df %>% pivot_longer(cols = c("R1","R2"), values_to = "VALUE")
    # A tibble: 6 x 3
      CODE  name  VALUE
      <chr> <chr> <int>
    1 A     R1        0
    2 A     R2        1
    3 B     R1        1
    4 B     R2        1
    5 C     R1        0
    6 C     R2        0
    
    colnames(df)[1:2] <- c("CODE1", "CODE2"); #to change the column names, dataframe 
    #with duplicate column names is not a good idea.
    

    您可以找到pivoting here @ https://tidyr.tidyverse.org/articles/pivot.html的全面概述

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2021-02-05
      相关资源
      最近更新 更多