[Rd] 'data.frame' method for base::rep()

David Winsemius dwinsemius at comcast.net
Wed Aug 3 16:54:52 CEST 2011


On Aug 3, 2011, at 2:45 AM, Liviu Andronic wrote:

> Hello David
>
>
> On Tue, Aug 2, 2011 at 4:14 PM, David Winsemius <dwinsemius at comcast.net 
> > wrote:
>>> x <- data.frame(a = as.Date('2000-01-01'), b=as.Date('2001-01-01'))
>>> x$d <- x$a -x$b
>>> require(mefa)
>>> rep(x, 2)
>>           a          b    d
>> 1 2000-01-01 2001-01-01 -366
>> 2 2000-01-01 2001-01-01 -366
>>> str(rep(x,2))
>> 'data.frame':   2 obs. of  3 variables:
>>  $ a: Date, format:  ...
>>  $ b: Date, format:  ...
>>  $ d: num  -366 -366   # notice that a difftime object has lost its  
>> class
>>
> Nice catch. Thanks for pointing it out.
>
>
>> # Whereas using the [rep(. , .) , ] approach does preserve the  
>> difftime
>> class.
>>> str(x[rep(1,2) , ])
>> 'data.frame':   2 obs. of  3 variables:
>>  $ a: Date, format:  ...
>>  $ b: Date, format:  ...
>>  $ d:Class 'difftime'  atomic [1:2] -366 -366   # leap year
>>  .. ..- attr(*, "units")= chr "days"
>>
> The above is nice. I wouldn't have thought of it.
>
>
>> Since that works out of the box with fewer potential side-effects,  
>> I am not
>> sure a new method is needed.
>>
> Your solution still seems more like an obscure side-effect of
> subsetting than an intuitive feature, in the sense that before trying
> it out the average user would probably first turn to base::rep() when
> in need to replicate a df, and then (perhaps) to
> mefa:::rep.data.frame() (with all the associated confusion and
> pitfalls). I would tend to believe that if there is a clean R-ish way
> to implement a base::rep.data.frame() it could still be useful.

To me that _is_ the R-ish way. It did not seem at all obscure.  
Duplicating column numbers also a way to replicate columns or  
rearrange them:

Try:

xtest=data.frame(a=letters[1:10], b=1:10)
xtest[ , c(1,2,2,1)]

-- 
David.



More information about the R-devel mailing list