[R] Repeat elements of matrix based on vector counts

Sarah Goslee sarah.goslee at gmail.com
Thu Dec 13 17:15:25 CET 2012


Hi Sarah,

If I understand your requirements correctly, the easiest thing to do
is approach it from a different direction:
df3a <- merge(df1, df2)

But you can also use rep for this simple example because plot.id in
df2 is sorted:
nindex <- table(df1$plot.id)
df3b <- df2[rep(1:length(nindex), times=nindex),]

Thanks for the reproducible example,
Sarah

On Thu, Dec 13, 2012 at 9:15 AM, Sarah Haas <haaszoology at gmail.com> wrote:
> I have two dataframes (df) that share a column header ("plot.id").  In the
> 1st df, "plot.id" records are repeated a variable number of times based on
> the number of trees monitored within each plot. The 2nd df only has a
> single record for each "plot.id", and contains a variable named "load" that
> is collected at the plot-level and is only listed once per plot record.
>
> *OBJECTIVE:*  I need to repeat the "load" values from the 2nd df based on
> how many times "plot.id" is repeated in the 1st df (all plots are repeated
> a different number of times). My example dfs are below:
>
> ************************************************************************************************
>      df1 <- data.frame(plot.id = rep(c("plot1", "plot2", "plot3"),
> c(3,2,5)),
>                  tree.tag = c(111,112,113,222,223,333,334,335,336,337))
>
>      df2 <- data.frame(plot.id = c("plot1", "plot2", "plot3"), load=c(17,
> 6, 24))
> ************************************************************************************************
>
> I have gotten close to solving this, but alas I'm on day 2 of
> problem-shooting and can't get it! Thanks for any help you might provide.
>
> --Sarah
>
>         [[alternative HTML version deleted]]
>

--
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list