【问题标题】:Reshaping a column from a data frame into several columns using R [duplicate]使用R将数据框中的一列重塑为几列[重复]
【发布时间】:2012-12-25 11:37:22
【问题描述】:

我有一个如下所示的数据库:

start<-as.POSIXct("2012-01-15")
interval<-60
end<-start+as.difftime(31,units="days")
date<-seq(from=start,by=interval*60, to=end) # date/time information
l<-length(date)

stations<-as.factor(rep(1:3,len=l)) # stations
df<-data.frame(date,stations) # data frame

我想要将此数据框中的站列重塑为几列(在本示例中为 3 列),并计算每个日期/时间行中每个站记录的时间数。但是,我想保留数据库中的原始日期/时间列。如果一个电台没有记录在一个特定的日期/时间,那么我想分配一个零值。

理想情况下,我想要这样的输出:

date              1   2   3
2012-01-15 0:00   1   0   0
2012-01-15 1:00   0   1   0
2012-01-15 2:00   0   0   1
2012-01-15 3:00   1   0   0
2012-01-15 4:00   0   1   0
2012-01-15 5:00   0   0   1
2012-01-15 6:00   1   0   0
2012-01-15 7:00   0   1   0
2012-01-15 8:00   0   0   1
2012-01-15 9:00   1   0   0
2012-01-15 10:00  0   1   0

【问题讨论】:

    标签: r datetime reshape


    【解决方案1】:

    您可以尝试使用库 reshape2 中的函数 dcast()

    library(reshape2)
    dcast(df,date~stations,length)
                       date 1 2 3
    1   2012-01-15 00:00:00 1 0 0
    2   2012-01-15 01:00:00 0 1 0
    3   2012-01-15 02:00:00 0 0 1
    4   2012-01-15 03:00:00 1 0 0
    

    【讨论】:

      【解决方案2】:

      你可以使用函数xtabs:

      xtabs( ~ date + stations, df)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-11
        • 1970-01-01
        • 1970-01-01
        • 2016-12-11
        • 2021-08-05
        • 1970-01-01
        • 2014-10-10
        • 2015-09-30
        相关资源
        最近更新 更多