rfrequency-distributiontwo-way

Two-way frequency distribution table for a quantitive data in R


I'm having difficult time to crate a two-way frequency distribution table for a tree diameter-height data. I have a dataset like below

dbh(cm) tht(m)
3   53.35
19  13.37
27  16.53
22  17.8
9   8.33
10  8.76
24  15.62
44  30.3
17  14.91
10  8.93

I need to create a frequency distribution table for this data with classes for both columns. My class bounds are like,

for diameter:

8 - 11.9
12 - 15.9
16 - 19.9 and so.

for height:

3 - 4.9
5 - 6.9
7 - 8.9 and so.

So I have thousands of rows of data and summing up each frequency in itself is a total pain. I wrote the following lines (dbh represents diameter and tht is height);

> data <- read.csv('data.csv')
> diameter <- data$dbh
> range(diameter)
[1]  6.0 60.5
> breaks <- seq(6, 61, by=4)
> diameter.cut <- cut(diameter, breaks, right = FALSE)
> diameter.frq <- table(diameter.cut)
> cbind(diameter.frq)
        diameter.frq
[6,10)            35
[10,14)           77
[14,18)           59
[18,22)           25
[22,26)           25
[26,30)           51
[30,34)           38
[34,38)           28
[38,42)           21
[42,46)           22
[46,50)           14
[50,54)            2
[54,58)            6
> 

I can do the same thing to the tree height (tht). But the problem is how do I create a 'cross frequence table'

For example: there are 35 trees in [6,10) diameter class. But I need to distribute these 35 trees into each height class. Let's say 12 of these trees belong to [3,5) height class, 8 of them in [5,7)...etc.

P.S: I'm pretty new in R. So my problem might seem pretty dummy but I really digged the internet before I post here. I'm sorry for that.


Solution

  • Did you mean this? After tweaking your code I got...

    library(dplyr)
    
    df %>%
      mutate(diameter.cm = cut(diameter.cm, seq(range(diameter.cm)[1], range(diameter.cm)[2]+4, by=4), right = F),
             height.m = cut(height.m, seq(range(height.m)[1], range(height.m)[2]+2, by=2), right = F)) %>%
      group_by(diameter.cm, height.m) %>%
      tally()
    

    Output is:

      diameter.cm height.m        n
    1 [3,7)       [52.3,54.3)     1
    2 [7,11)      [8.33,10.3)     3
    3 [15,19)     [14.3,16.3)     1
    4 [19,23)     [12.3,14.3)     1
    5 [19,23)     [16.3,18.3)     1
    6 [23,27)     [14.3,16.3)     1
    7 [27,31)     [16.3,18.3)     1
    8 [43,47)     [28.3,30.3)     1
    

    Sample data:

    df <- structure(list(diameter.cm = c(3L, 19L, 27L, 22L, 9L, 10L, 24L, 
    44L, 17L, 10L), height.m = c(53.35, 13.37, 16.53, 17.8, 8.33, 
    8.76, 15.62, 30.3, 14.91, 8.93)), class = "data.frame", row.names = c(NA, 
    -10L))