【问题标题】:Data reshape in R [duplicate]R中的数据重塑[重复]
【发布时间】:2016-05-31 07:37:35
【问题描述】:

我是 R 新手。所以请帮我弄清楚以下问题。

我的数据如下。

> CheckIn    - ID 
> 2016/Jan/1 - 100 
> 2016/Feb/1 - 100
> 2014/Jan/1 - 100 
> 2014/Jan/1 - 101 
> 2015/Feb/1 - 100

我想从上面的数据中找出以下表格

     Jan - Feb - Mar 
2014  2  -  0  - 0
2015  0  -  1  - 0
2016  1  -  1  - 0

在 R 中可以吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以试试

    library(data.table)
    setDT(df1)[, c("Year", "Month") := {dt <- as.Date(CheckIn, "%Y/%b/%d"); list(format(dt, "%Y"), format(dt, "%b"))}]
    dcast(df1, Year~Month, value.var="ID", length)
    

    【讨论】:

      【解决方案2】:

      你可以试试 reshape 包中的 cast 函数

      library("reshape") 
      
      格式化数据以便正确存储在数据表中
      my_data=data.table(CheckIn=c("2016/Jan/1","2016/Feb/1","2014/Jan/1","2014/Jan/1","2015/Feb/1"),ID=c("100","100","100","101","100"))   
      my_data[,"Year":=substr(CheckIn,1,4)]
      my_data[,"Month":=substr(CheckIn,6,8)]
      my_data[,"Frequency":=as.numeric(substring(CheckIn,10))] 
      
      使用 cast 得到你想要的结果
      cast(my_data,Year~Month,value="Frequency")
      

      【讨论】:

        猜你喜欢
        • 2014-11-09
        • 2017-04-05
        • 1970-01-01
        • 2010-12-04
        • 2017-09-06
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多