简体   繁体   中英

Grouping rows in R based on numbers

I have a data frame where one column is the site number, but each site number is repeated 5 times, this is some of it:

Site<-c(1,1,1,1,1,2,2,2,2,2)
Species1<-c(5,1,9,2,2,7,5,6,4,9)
Species2<-c(0,2,7,5,0,4,8,4,1,5)
Species3<-c(3,2,1,0,5,1,1,6,2,4)

There are 50 sites, each repeated five times (data was collected at those sites on five different days). I want to group the rows with the same site number to be able to calculate species numbers at those sites. This should create 1 row for each site. Edit:

 Site<-c(1,2)
 Species1<-c(19,31)
 Species2<-c(14,22)
 Species3<-c(11,14) 

Thanks in advance!

We can use dplyr . We group by 'Site' and get the sum of all the other columns using summarise_each .

library(dplyr)
df1 %>% 
    group_by(Site) %>% 
    summarise_each(funs(sum))

or with data.table . We convert the 'data.frame' to 'data.table' ( setDT(df1) , group by 'Site', we loop ( lapply(.SD,.. ) through the columns and get the sum .

setDT(df1)[, lapply(.SD, sum), by = Site]

data

df1 <- data.frame(Site, Species1, Species2, Species3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM