0

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)
}
Jeppe Olsen
  • 968
  • 8
  • 19

1 Answers1

1

in your function, you have to change the logical operator == to %in% in order to compare with vectors.

fun <- function(sp){
  a <- x[x$b %in% sp,] 
  return(a)
}

sp <- "dog"
fun(sp)
# a   b
# 4 4 dog
# 8 8 dog
sp <- c("dog", "ant")
fun(sp)
# a   b
# 1 1 ant
# 4 4 dog
# 5 5 ant
# 8 8 dog
loki
  • 9,816
  • 7
  • 56
  • 82