【问题标题】:Use column values to create wide format table [duplicate]使用列值创建宽格式表[重复]
【发布时间】:2017-09-11 21:44:52
【问题描述】:

我有以下数据框:

class   outcome   count    total
A       TP        5        20
A       FP        5        20
A       TN        5        20
A       FN        5        20
B       TP        10       40
B       FP        10       40
B       TN        10       40
B       FN        10       40

我本质上想要的是所谓的宽格式,即

type    TP    FP    TN    FN    total
A       5     5     5     5     20 
B       10    10    10    10    40

我几乎可以这样做:

> dcast(test,test$outcome ~ test$class)
Using class...outcome...count....total as value column: use value.var to override.
  .  A       FN        5        20  A       FP        5        20  A       TN        5        20  A       TP        5        20
1 .  A       FN        5        20  A       FP        5        20  A       TN        5        20  A       TP        5        20
   B       FN        10       40  B       FP        10       40  B       TN        10       40  B       TP        10       40
1  B       FN        10       40  B       FP        10       40  B       TN        10       40  B       TP        10       40

我现在为每种结果类型都有一个列,但我缺少列名、重复行和我想要的列标题(TP、FP、TN、FN)作为列值...仍然。

所以也很遥远。

dcast 甚至可以做到这一点吗?

【问题讨论】:

    标签: r aggregate reshape


    【解决方案1】:

    下面是使用tidyr 使用spread 的方法:

    library(tidyr)
    df1 <-read.table(text="class   outcome   count    total
    A       TP        5        20
    A       FP        5        20
    A       TN        5        20
    A       FN        5        20
    B       TP        10       40
    B       FP        10       40
    B       TN        10       40
    B       FN        10       40",header=TRUE, stringsAsFactors=FALSE)
    
    library(tidyr)
    spread(df1,outcome,count)
    
      class total FN FP TN TP
    1     A    20  5  5  5  5
    2     B    40 10 10 10 10
    

    这是dcast 解决方案:

    dcast(df1, class +total ~ outcome, value.var="count")
      class total FN FP TN TP
    1     A    20  5  5  5  5
    2     B    40 10 10 10 10
    

    【讨论】:

    • 这太棒了。这正是我一直在寻找的,也是我认为 dcast 应该做的。谢谢。
    • @brucezepplin 我刚刚添加了dcast 解决方案。我发现gather 更容易理解,所以我开始使用它。
    【解决方案2】:

    在基础 R 中使用 reshape(其中 df 是您的数据框)

    reshape(df, idvar = c("class", "total"), timevar = "outcome", direction = "wide")
    
    #  class total count.TP count.FP count.TN count.FN
    #1     A    20        5        5        5        5
    #5     B    40       10       10       10       10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2022-07-12
      • 2019-10-24
      • 1970-01-01
      • 2020-05-01
      相关资源
      最近更新 更多