Home > Back-end >  Add up values in one column that fulfill condition in two other columns R
Add up values in one column that fulfill condition in two other columns R

Time:10-25

I am a beginner in R, can't find an easy solution to my problem. I have a three-column table: Location, Vegetation.type, Area.

Each observation consists of a patch of vegetation. Each sampling site ("Location") is composed by numerous patches of vegetation, and within the same site, some patches contain the same vegetation type. I would like to add up the area of all the patches with equal Vegetation.type that occur within the same Location.

Therefore, the resulting data frame I expect would have for each Location, as many rows as Vegetation.types there are. And the Area value would present the total extension of each Vegetation.type within each Location.

CodePudding user response:

You can do this using base R using the aggregate() function or using the dplyr library by first grouping by the Location and Vegitation.type then summing the Area.

Data

set.seed(123)
df <- data.frame(Location = sample(LETTERS[1:2], 15, replace = TRUE),
                 Vegitation.type = sample(c("grass", "tree", "flower"), 15, replace = TRUE),
                 Area = runif(15))

Base:

aggregate(Area ~ Location   Vegitation.type, df, sum)

Dplyr

library(dplyr)
df %>% 
  group_by(Location, Vegitation.type) %>% 
  summarize(total_Area = sum(Area))

Output:

#  Location Vegitation.type total_Area
#  <chr>    <chr>                <dbl>
#1 A        flower               1.55 
#2 A        grass                1.43 
#3 A        tree                 1.44 
#4 B        flower               0.320
#5 B        grass                0.828
#6 B        tree                 1.86 
  •  Tags:  
  • r
  • Related