Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sum values in a column, grouped by names in rows in R, without listing each name?

Tags:

r

aggregate

How do I use R to find sums for values by species? I have 62 species names and want to add the basal area for each species in a habitat. I tried

aggregate(file name, species, FUN=sum, simplify=TRUE)

and many variations on this but it always says that it cannot find species (a column header in my data set). The list is too long to add as input; I want the program to use my column information. My data set looks something like this:

Species      BA
sp1          0.5
sp1          0.2
sp2          0.1
like image 349
Kim Avatar asked Jan 14 '23 20:01

Kim


1 Answers

First read the data into a data frame, then use aggregate.

# You would read from the file instead.
x <- read.table(header=T, file=textConnection("Species      BA
sp1          0.5
sp1          0.2
sp2          0.1
"))

> aggregate(.~Species, data=x, FUN=sum)
  Species  BA
1     sp1 0.7
2     sp2 0.1
like image 52
Matthew Lundberg Avatar answered Jan 21 '23 16:01

Matthew Lundberg