[R] How to create a data.frame "like" another, but longer?

Kaspar Pflugshaupt pflugshaupt at geobot.umnw.ethz.ch
Wed Dec 19 15:33:25 CET 2001


On 19.12.2001 15:03 Uhr, Douglas Bates wrote:

> Use indexing.  A surprising result in the S language is that a
> `subset' can be longer than the original set.
> 
> In your case
> 
> ind <- c(1:nrow(mydata), rep(1, n - nrow(mydata)))
> mydata2 <- mydata[ind, ]
> # overwrite the data here
> 
> The reason for making the indices of the form 1, 2, 3, 1, 1, 1, ..., 1
> is to ensure that all levels of factors get represented in the
> extracted data.  That may be unnecessary.  You could experiment with
> 
> mydata2 <- mydata[rep(1, n), ]
> 
> and see if that works properly.

Thanks! I guessed there would be something simple like this... There seems
to be no end to the surprisingly elegant indexing solutions in R!

I tried it out and ended up with

f.expand.df <- function(df, newrows)
  {
    oldrows <- nrow(df)
    new.index <- rep(1:oldrows, newrows/oldrows+1)[1:newrows]
    df[new.index,]
  }

which just recycles the dataframe's rows enough times and cuts off the
excess.

Thanks again for the tip


Kaspar


-- 

Kaspar Pflugshaupt
Geobotanisches Institut
Zuerichbergstr. 38
CH-8044 Zuerich

Tel. ++41 1 632 43 19
Fax  ++41 1 632 12 15

mailto:pflugshaupt at geobot.umnw.ethz.ch
privat:pflugshaupt at mails.ch
http://www.geobot.umnw.ethz.ch

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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