[R] How to make matrix missing data 0

William Dunlap wdunlap at tibco.com
Thu Jul 7 21:44:32 CEST 2011


Make factors out of the dayOfYear and HourOfDay
columns and specify the levels you want.  Then
pass the factors to tapply.

E.g., you may have something like
> d <- data.frame(Season=c(1,1,3,4),
                  Type=c(20,15,15,20),
                  Speed=11:14)
> tapply(d$Speed, d[c("Season","Type")], mean)
      Type
Season 15 20
     1 12 11
     3 13 NA
     4 NA 14
and you are missing the row for Season==2 and perhaps
for some of the types.  Making factors out of Season
and Type (with the desired levels) lets you get the
missing rows and columns in the output of tapply:

> d$Season <- factor(d$Season, levels=c(1,2,3,4))
> d$Type <- factor(d$Type, levels=c(5,10,15,20))
> tapply(d$Speed, d[c("Season","Type")], mean)
      Type
Season  5 10 15 20
     1 NA NA 12 11
     2 NA NA NA NA
     3 NA NA 13 NA
     4 NA NA NA 14

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of xin123620
> Sent: Thursday, July 07, 2011 12:21 PM
> To: r-help at r-project.org
> Subject: [R] How to make matrix missing data 0
> 
> Dear All, 
> 
> I am trying to analysis traffic data with one timestamp 
> column and speed
> column. This data set contains six years data; for each year, 
> I want to make
> a matrix in (day of the year) * (hour)
>          0  1  2   . . . 23
> 1    
> 2
> .
> .
> 365
> 
> However random day's record is missing(e.g. there are 40 
> missing records in
> 2005 data set), when I tried to use tapply function, matrix 
> came out is
> 326*23 table and there were no N/A remind me which day is 
> missing data.  
> 
> Can you give some hints to make a 366*24 table please? Any help is
> appreciated.
> 
> Jessica
> 
> 
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/How-to-make-matrix-missing-data-
0-tp3652352p3652352.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list