A forest inventory problem

Sometimes actions that are easy using “group by” in SQL aren’t obvious in R or appear to need too many lines of code using “tapply”, “aggregate” or “by” in R.

Splitting and substituting back into the original data frame can work neatly in some cases.

Take this example that is also mentioned in the document available here. A study measures the diameter at breast height and the heights of trees. The trees may have multiple stems. The researcher wants to work with the total sum of the basal area per individual, the maximum height of the tallest stem and the maximum diameter of the stems.

A trial data set can be simulated with.

cuad_Id<-sort(sample(1:180,replace=T,1000))
esp_Id<-sample(1:10,replace=T,1000)
ind_Id<-1:1000
dap<-round(rnorm(1000,30,5),1)
alt<-round(dap/2+rnorm(1000,0,2),2)
tallos<-data.frame(cuad_Id,ind_Id,esp_Id,dap,alt)

Add multiple stems per individual.

tallos2<-tallos[sample(1:1000,500,rep=T),]
tallos2$dap<-round(rnorm(500,30,5),1)
tallos2$alt<-round(tallos2$dap/2+rnorm(500,0,2),2)

tallos<-rbind(tallos,tallos2)
tallos<-tallos[order(tallos$ind_Id),]
row.names(tallos)<-1:1500

So the simulated data looks like this …

fiig141.png

The basal area (ab) in m² per stem can be calculated using ..

tallos<-data.frame(tallos,ab=pi*(tallos$dap/200)^2)

To achieve the result substitute the sum of the basal area for each individual using split and tapply.

split(tallos$ab,tallos$ind_Id)<-tapply(tallos$ab,tallos$ind_Id,sum)

Use the same method to substitute the maximum heights and diameters

split(tallos$alt,tallos$ind_Id)<-tapply(tallos$alt,tallos$ind_Id,max)
split(tallos$dap,tallos$ind_Id)<-tapply(tallos$dap,tallos$ind_Id,max)

Now just remove duplicated rows.

tallos<-tallos[!duplicated(tallos),]

Done.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s