I want to subset a dataframe based on a character string. I can make this work with one length character string, but not with a more than one (unknown) length character string. Any ideas?
x <- data.frame(a=1:8, b=rep(c("ant", "bee", "beetle", "dog"),2))
fun <- function(sp){
a <- x[x$b==sp,]
return(a)
}
sp <- "dog"
fun(sp)
a b
4 4 dog
8 8 dog
This works. I get all the rows with dog.
sp <- c("dog", "ant")
fun(sp)
[1] a b
<0 rows> (or 0-length row.names)
This doesnt work. I want the rows with dog and ant, but get none.
Solution: just use %in% instead of == (Thanks to docendo-discimus)
fun <- function(sp){
a <- x[x$b%in%sp,]
a)
}