in

Collapsing data to a single row based on ID


I am tryng to collapse my data into a single row based on ID. The data consists of IDs (site locations) and the amount of species found in each site (SP1, SP2 etc). At the moment their are multiple IDs depending on how many individual species are found on that site and I want to collapse the data down so I just have a single row based on the site ID.

My data currently looks similar to this:

my_data <- data.frame(ID = c(1,2,3,3,3,4,4,4,4),
                      SP1 = c(10,15,0,0,0,0,0,0,10),
                      SP2 = c(0,0,5,0,0,8,0,0,0),
                      SP3 = c(0,0,0,20,0,0,4,0,0),
                      SP4 = c(0,0,0,0,0,0,0,12,0),
                      SP5 = c(0,0,0,0,6,0,0,0,0))

and I want to get it to look like this:

my_data2 <- data.frame(ID = c(1,2,3,4),
                       SP1 = c(10,15,0,10),
                       SP2 = c(0,0,5,8),
                       SP3 = c(0,0,20,4),
                       SP4 = c(0,0,0,12),
                       SP5 = c(0,0,6,0))

I think the best way to do it would be something along the lines of the code below but not sure on what to include in the summarise

my_data %>%
        group_by(ID)
        summarise()



Source: https://stackoverflow.com/questions/70723237/collapsing-data-to-a-single-row-based-on-id

Amazfit Smartwatches Deals That You Don’t Want to Miss

TikTok clone app built with React for educational purposes