-1

I have a tree list with diameters for each tree (among many other variables). I'm trying to streamline the process of adding a new column that gives a diameter class based on each tree's diameter and I think it can be done with indexing and/or a for loop but I'm not strong with either of these skills. Diameters range from 0-80 cm. I want to put these into 2-cm classes where a tree between 0-0.9 is class "0", a tree 1.0-2.9 is class "2", a tree 3-4.9 is class "4" etc all the way to 80 cm. Here is a small snapshot of my data:

     Unit Plot Treatment           Year Species2 DBHmet
2     1    1        WB Post-treatment     PIPO 42.164
3     1    1        WB Post-treatment     PIPO 24.384
4     1    1        WB Post-treatment     PIPO 16.764
5     1    1        WB Post-treatment     PIPO 23.114
6     1    1        WB Post-treatment     PIPO 41.148
7     1    1        WB Post-treatment     PIPO  4.826
8     1    1        WB Post-treatment     PIPO 17.780
10    1    1        WB    Pre-harvest     PIPO 11.176
11    1    1        WB    Pre-harvest     PIPO 42.164
12    1    1        WB    Pre-harvest     PIPO  3.302
13    1    1        WB    Pre-harvest     PIPO 12.192

How can I quickly add an additional column that places the "DBHmet" into 2cm classes, as described above?

KBo
  • 43
  • 3
  • 1
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data and the desired output for that data. That way possible solutions can be easily tested and verified. – MrFlick Nov 16 '17 at 21:33
  • Thanks for the nudge. I hope what I added above helps. – KBo Nov 16 '17 at 22:06

1 Answers1

0

From the snapshot, I assume, that you have a dataframe/table and not a list. Assuming this, the following will change the DBHmet values to the desired 2 cm classes:

> data <- data.frame(DBHmet = c(0.0, 0.9, 1.0, 2.9, 3.0, 4.9, 80.0),
+                    otherVar = rep("a", 7))
> data$DBHmet_2cm <- floor(((data$DBHmet + 1)/2))*2
> data
  DBHmet otherVar DBHmet_2cm
1    0.0        a          0
2    0.9        a          0
3    1.0        a          2
4    2.9        a          2
5    3.0        a          4
6    4.9        a          4
7   80.0        a         80
You-leee
  • 550
  • 3
  • 7
  • Thank you, this did exactly what I needed! I was not familiar with the floor function before, I will be sharing this with my colleagues! Many thanks. – KBo Nov 17 '17 at 16:34