使用R将数据帧中的列重新形成几列 [英] Reshaping a column from a data frame into several columns using R
问题描述
我有一个数据库,如下所示:
I have a database that looks like this:
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列),并计算每个站点在每个日期/时间排。但是,我想保留数据库中的原始日期/时间列。如果一个电台没有记录在一个特定的日期/时间,那么我想分配一个值为零。
What I would like is to reshape the station column from this data frame into several columns (in this example it will be 3 columns) and calculate the number of time each station was recorded in each date/time row. However, I would like to keep the original date/time column from the data base. If a station was not recorded in one specific date/time, then I want to assign a value of zero.
理想情况下,我想要一个这样的输出: p>
Ideally, I would like an output like this:
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
推荐答案
您可以尝试使用函数 dcast()
从库 reshape2
。
You can try to use function dcast()
from library reshape2
.
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
这篇关于使用R将数据帧中的列重新形成几列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!