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

David Winsemius dwinsemius at comcast.net
Tue Aug 2 16:14:59 CEST 2011


On Aug 2, 2011, at 7:55 AM, Liviu Andronic wrote:

> Dear R developers
> Would you consider adding a 'data.frame' method for the base::rep
> function? The need to replicate a df row-wise can easily arise while
> programming, and rep() is unable to handle such a case. See below.
>> x <- iris[1, ]
>
x[ rep(1,2), ] # "works"

> I found a 'rep.data.frame' function in package 'mefa' [2], but I think
> it would be nice to have it in base R. In any case, the code used by
> the method is very simple.
>> require(mefa)
> Loading required package: mefa
> mefa 3.2-1 	 2011-05-13
>> mefa:::rep.data.frame
> function (x, ...)
> as.data.frame(lapply(x, rep, ...))
> <environment: namespace:mefa>
>
> And here's the example above:
>> rep(x, 2)
>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
> 1          5.1         3.5          1.4         0.2  setosa
> 2          5.1         3.5          1.4         0.2  setosa
>

I do not think the mefa 'rep.data.frame' code is a good example to  
replicate ... as it were. It strips classes from any column that does  
not have an associated 'rep' method, and the repetoire (we are in some  
kind of self-referential loop here) of rep.* methods is pretty meager.

My initial thought was that the expected functionality would be found  
with "[" using the template:

  dfrm[rep(vec, times/each= vec2) , ]

It appears "[" proves would preserve classes for a much larger range.

methods("[")

 > 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

# 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"

Since that works out of the box with fewer potential side-effects, I  
am not sure a new method is needed.

-- 
David.
>
> Please le t me know what you think. Regards
> Liviu
>
> [1] http://finzi.psych.upenn.edu/R/library/mefa/html/rep.data.frame.html
> [2] http://cran.at.r-project.org/web/packages/mefa/index.html
>
>
> -- 


David Winsemius, MD
West Hartford, CT



More information about the R-devel mailing list