【问题标题】:Pivot columns in Data Frame数据框中的数据透视列
【发布时间】:2015-01-31 17:05:30
【问题描述】:

我有下面的数据框:

data<-data.frame(names= c("Bob","Bob", "Fred","Fred","Tom"), id =c(1,1,2,2,3),amount = c(100,200,400,500,700), status = c("Active","Not Active","Active","Retired","Active"))
data

 names id amount     status
1   Bob  1    100     Active
2   Bob  1    200 Not Active
3  Fred  2    400     Active
4  Fred  2    500    Retired
5   Tom  3    700     Active

我想旋转“状态”列,以便“金额”数据出现在新状态列下,结果如下所示:

names     id    Active    Not Active  Retired
Bob       1      100         200
Fred      2      400                   500
Tom       3      700

这可能吗?最好的方法是什么?

【问题讨论】:

  • 在任何真实的东西中(阅读:不是 Excel),这是 “将数据从长格式重塑为宽格式”:library(tidyr) ; spread(data, status, amount)

标签: r


【解决方案1】:

我现在不得不将评论变成答案。这是 Hadleyverse 版本:

library(tidyr)
spread(data, status, amount)

##   names id Active Not Active Retired
## 1   Bob  1    100        200      NA
## 2  Fred  2    400         NA     500
## 3   Tom  3    700         NA      NA

【讨论】:

    【解决方案2】:

    这是使用reshape2 包中的dcast 的解决方案:

    library(reshape2)
    
    dcast(data, names + id ~ status, value.var="amount")
    
    #   names id Active Not Active Retired
    # 1   Bob  1    100        200      NA
    # 2  Fred  2    400         NA     500
    # 3   Tom  3    700         NA      NA
    

    【讨论】:

      【解决方案3】:

      这将是基本方法:

      > xtabs(amount~names+status, data=data)
            status
      names  Active Not Active Retired
        Bob     100        200       0
        Fred    400          0     500
        Tom     700          0       0
      

      【讨论】:

        【解决方案4】:

        这是另一个base R 选项

         reshape(data, idvar=c('names', 'id'), timevar='status', direction='wide')
         #  names id amount.Active amount.Not Active amount.Retired
         #1   Bob  1           100               200             NA
         #3  Fred  2           400                NA            500
         #5   Tom  3           700                NA             NA
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-07
          • 2021-06-10
          • 2023-03-11
          • 1970-01-01
          • 1970-01-01
          • 2018-02-23
          • 2020-01-07
          • 1970-01-01
          相关资源
          最近更新 更多