I have a dataframe, df1, that looks like the following:
| sample | 99_Ape_1 | 93_Cat_1 | 87_Ape_2 | 84_Cat_2 | 90_Dog_1 | 92_Dog_2 |
|---|---|---|---|---|---|---|
| A | 2 | 3 | 1 | 7 | 4 | 6 |
| B | 5 | 9 | 7 | 0 | 3 | 7 |
| C | 6 | 8 | 9 | 2 | 3 | 0 |
| D | 3 | 9 | 0 | 5 | 8 | 3 |
I want to consolidate the dataframe by summing the values based on animal present in the header row, i.e. by "Ape", "Cat", "Dog", and end up with the following dataframe:
| sample | Ape | Cat | Dog |
|---|---|---|---|
| A | 3 | 10 | 10 |
| B | 12 | 9 | 10 |
| C | 15 | 10 | 3 |
| D | 3 | 14 | 11 |
I have created a list that represents all the animals called "animals_list"
I have then created a list of dataframes that subsets each animal into a separate dataframe with:
animals_extract <- c()
for (i in 1:length(animals_list)){
species_extract[[i]] <- df1[, grep(animals_list[i], names(df1))]
}
I am then trying to sum each variable in the row by sample:
for (i in 1:length(species_extract)){
species_extract[[i]]$total <- rowSums(species_extract[[i]])
}
and then create a dataframe 'animal_total' by binding all values in the new 'total' column.
animal_total <- NULL
for (i in 1:length(species_extract)){
animal_total[i] <- cbind(species_extract[[i]]$total)
}
Unfortunately, this doesn't seem to work at all and I think I may have taken the wrong route. Any help would be really appreciated!
EDIT: my dataframe has over 300 animals, meaning incorporating use of my list of identifiers (animals_list) would be highly appreciated! I would also note that some column names do not follow the structure, "number_animal_number" and therefore I can't use a repetitive search (sorry!).