[R] A couple of little R things I can't figure out (column percents, regression with lagged variables)

Jason Turner jasont at indigoindustrial.co.nz
Tue Feb 12 10:38:12 CET 2002


Long one - sorry in advance.

On Tue, Feb 12, 2002 at 12:37:55AM -0600, Paul Johnson wrote:
> 1.I'm able to produce a cross tabulation table showing counts with 
> either table or xtabs.  But I want column percentages for ...

apply(hmm,2,function(zz){zz/sum(zz)}) * 100


> 2. A student said here's  y, a vector representing a time series, and 
> here's x, a vector representing a time series. I want to do a 
> conventional regression of y on the lag of x. In sas you do xlag=lag(x) 
...
> I see the lag function in ts, but when I use it, it doesn't change x, so 
> obviously I don't see the point of that.

In R, lag(x) shifts the "start" attribute of the time series, but
doesn't alter the data per se.  This is why you get the same before
and after picture, when you just look at it as a vector.  

To see the effect of lagging data, it only makes sense to  compare 
one lagged time series with another time series, like so...

(using x and y above)

> library(ts)
> yt<-ts(y)
> xt<-ts(x)

> lagxt<-lag(xt)
> x1<-ts.union(yt,xt,lagxt)
> x1
Time Series:
Start = 0 
End = 10 
Frequency = 1 
   yt xt lagxt
 0 NA NA     1
 1  2  1     3
 2  4  3     1
 3  1  1     3
 4  4  3     1
 5  2  1     3
 6  4  3     1
 7  1  1     3
 8  4  3     4
 9  2  4     4
 10  4  4    NA

Note the "start" value of x1.

If you want to use lm and friends, you must make them
"plain vanilla" vectors - the time series part confuses
lm.  One way...

> d1<-data.frame(x1)
> r1<-lm(yt ~ lagxt, data=d1)


...
> One sidenote is that summary does not include any mention of the fact 
> that 1 observation was lost due to missing value. That seems bad to me.
...

It does 

> summary(r1)

..[lots of stuff removed]...

Residual standard error: 1.171 on 7 degrees of freedom
Multiple R-Squared: 0.3143,	Adjusted R-squared: 0.2163 
F-statistic: 3.208 on 1 and 7 DF,  p-value: 0.1164 
                      ^^^^^^^^^^

though I'll be the first to admit it doesn't jump up and 
bite you  ;)

Cheers

Jason
-- 
Indigo Industrial Controls Ltd.
64-21-343-545
jasont at indigoindustrial.co.nz
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list