Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use the "function" command to call certain rows of a dateframe?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading