Federico C
Federico C

Reputation: 132

Select certain row names

Is there any way to select all rows from a dataframe whose name in one column don't have a word?

Example:

From this data frame

Organism    Value
Boa (sick)  3
Cat         1
Cat (sick)  2
Wolf        2
Wolf (sick) 8
Crow        4

I want the rows without (sick) in its name:

Organism    Value
Cat         1
Wolf        2
Crow        4

I know that the data is in the wrong format and it would be better to have a third column for "health" but I have to work with the data that I have.

Upvotes: 1

Views: 1434

Answers (3)

seancarmody
seancarmody

Reputation: 6290

Yet another very similar alternative:

subset(d, grepl("(sick)", Organism, fixed=TRUE))

Upvotes: 0

sgibb
sgibb

Reputation: 25736

d <- data.frame(Organism=c("Boa (sick)", "Cat", "Cat (sick)", "Wolf", "Wolf (sick)", "Crow"), Value=c(3, 1, 2, 2, 8, 4), stringsAsFactors=FALSE)

d[!grepl(pattern="(sick)", x=d$Organism, fixed=TRUE), ]
#  Organism Value
#2      Cat     1
#4     Wolf     2
#6     Crow     4

Upvotes: 7

shhhhimhuntingrabbits
shhhhimhuntingrabbits

Reputation: 7475

Try

df<-data.frame(Organism=c('Boa (sick)','Cat','Cat (sick)','Wolf','Wolf (sick)','Crow'),Value=c(3,1,2,2,8,4))
expel<-grep('(sick)',df$Organism)
if(length(expel)>0){
  df1<-df[-expel,]
}
df1
#  Organism Value
#2      Cat     1
#4     Wolf     2
#6     Crow     4

Upvotes: 1

Related Questions