How can I create a new dataframe with only the species that are present in multiple depths?

Viewed 53

I have a large number of species abundance samples taken at different depths. The data is arranged like:

df1 <- data.frame(sample = c('a', 'b', 'c', 'd', 'e','f','g','h','i'),
                  depth = c(10,20,30,10,20,30,10,20,30),
                  sp1 = c(1,0,0,2,0,0,5,0,0),
                  sp2 = c(1,4,6,5,3,1,5,6,4),
                  sp3 = c(0,0,0,0,2,0,0,0,0),
                  sp4 = c(1,0,5,4,3,7,8,4,1))

where the columns after sample and depth are indivdual species. I basically want to select only the species present in more than one depth and create a new dataframe looking at just these, like this:

df2 <- data.frame(sample = c('a', 'b', 'c', 'd', 'e','f','g','h','i'),
                  depth = c(10,20,30,10,20,30,10,20,30),
                  sp2 = c(1,4,6,5,3,1,5,6,4),
                  sp4 = c(1,0,5,4,3,7,8,4,1))

Any help would be much appreciated :)

1 Answers
library(dplyr)

df1 %>%
  select(1:2, starts_with('sp') & where(~ n_distinct(df1$depth[.x != 0]) > 1))

#   sample depth sp2 sp4
# 1      a    10   1   1
# 2      b    20   4   0
# 3      c    30   6   5
# 4      d    10   5   4
# 5      e    20   3   3
# 6      f    30   1   7
# 7      g    10   5   8
# 8      h    20   6   4
# 9      i    30   4   1
Related