[R] appending data to a dataframe

Duncan Murdoch murdoch at stats.uwo.ca
Tue Aug 31 14:13:36 CEST 2004


On Tue, 31 Aug 2004 14:05:59 +0200, Dewez Thomas <t.dewez at brgm.fr>
wrote :

>Dear R users,
>
>I am sorry to ask you such a pathetic newbie question, but how does one
>append data at the end of a data frame?

The rbind() function should work:  it adds rows to matrices and
dataframes.

However, I'd do something different for the problem you give:

>I am working with GRASS/R library, but the question is about R.
>I have a data.frame containing the following variables
>basinID, distoutlet, drainage_area, slope
>
>These variables are stored for all pixels of Grass Raster objects. For each
>drainage basin (basinID), I'd like to find the maximum of distoutlet. How
>can I store the pair of info (bv$ID, max(bv$distoutlet)) at each step of the
>for loop ?
>
>I presume something like this could do
>
>for (i 1:max(basinID)){
>bid <- i
>length <- max(distoutlet[which(basinID == I(i))])
>}
>
>But how do I handle the output and record bid and length in parallel in an
>object???

Appending a row at a time is very slow.  You'll find it much faster to
set up a matrix to hold the results in advance:

results <- matrix(NA, max(basinID), 2)
for (i in 1:max(basinID)) {
bid <- i
length <- max(distoutlet[which(basinID == i)])
results[i,] <- c(i, length)
}

Duncan Murdoch




More information about the R-help mailing list