I have a dataframe containing species presence/absence data across many sites. This is a basic representation of what it looks like.
df=data.frame(site=c("site1","site1","site1","site2","site2","site2"),
speciesA=c(0,1,0,1,1,0),speciesB=c(0,0,0,1,0,1),speciesC=c(1,0,1,1,1,1))
I’d like to be able to work on specific sites individually (aka specific rows with the same name in the site column).
I’m able to use subset to isolate one site.
subset(df[df$site=="site1", ])
I tried to use a function to do this for all sites without writing out the full code,
sitename<-function(s){
subset(df[df$site=="s", ])
}
sitename(site2)
But this returns <0 rows> (or 0-length row.names).
>Solution :
Your use of subset here is a bit redundant because you are indexing the data frame as well. You should either use
sitename <- function(s){
subset(df, site==s)
}
or
sitename <- function(s){
df[df$site==s, ]
}
along with
sitename("site1")