[R] Using transform to add a date column to a dataframe

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Dec 23 15:06:01 CET 2008


On Tue, 2008-12-23 at 05:24 -0800, Tom La Bone wrote:
> I would like to add a column to the airquality dataset that contains the date
> 1950-01-01 in each row. This method does not appear to work:
> 
> > attach(airquality)
> > data1 <- transform(airquality,Date=as.Date("1950-01-01"))
> 
> Error in data.frame(list(Ozone = c(41L, 36L, 12L, 18L, NA, 28L, 23L, 19L,  : 
>   arguments imply differing number of rows: 153, 1
>  
> I can't decipher what the error message is trying to tell me. Any
> suggestions on how to do this?

It says that the two arguments have different numbers of observations.
The reason for which should now be pretty obvious as you provided a
single Date whereas airquality has 153 observations.

You did read ?transform , which points out this "problem"? ;-)

Anyway, don't assume R recycles everything if it is not of sufficient
length to match other arguments. In this case, repeat the date as many
times as there are rows in airquality:

> data(airquality)
> data1 <- transform(airquality, Date = rep(as.Date("1950-01-01"),
nrow(airquality)))
> head(data1)
  Ozone Solar.R Wind Temp Month Day       Date
1    41     190  7.4   67     5   1 1950-01-01
2    36     118  8.0   72     5   2 1950-01-01
3    12     149 12.6   74     5   3 1950-01-01
4    18     313 11.5   62     5   4 1950-01-01
5    NA      NA 14.3   56     5   5 1950-01-01
6    28      NA 14.9   66     5   6 1950-01-01

Also, the attach(airquality) call in your example doesn't do anything
that affects your example so is redundant.

HTH

G

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20081223/b93647a9/attachment.bin>


More information about the R-help mailing list