Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: how to remove certain rows in data.frame

Tags:

r

subset

> data = data.frame(a = c(100, -99, 322, 155, 256), b = c(23, 11, 25, 25, -999))
> data
    a    b
1 100   23
2 -99   11
3 322   25
4 155   25
5 256 -999

For such a data.frame I would like to remove any row that contains -99 or -999. So my resulting data.frame should only consist of rows 1, 3, and 4.

I was thinking of writing a loop for this, but I am hoping there's an easier way. (If my data.frame were to have columns a-z, then the loop method would be very clunky). My loop would probably look something like this

i = 1
for(i in 1:nrow(data)){
  if(data$a[i] < 0){
    data = data[-i,]
  }else if(data$b[i] < 0){
    data = data[-i,]
  }else data = data
}
like image 895
Adrian Avatar asked Sep 12 '25 12:09

Adrian


2 Answers

 data [ rowSums(data == -99 | data==-999) == 0 , ]
    a  b
1 100 23
3 322 25
4 155 25

Both the "==" and the "|" (OR) operators act on dataframes as matrices, returning a logical object of the same dimensions so rowSums can succeed.

like image 80
IRTFM Avatar answered Sep 15 '25 01:09

IRTFM


Maybe this:

ind <- Reduce(`|`,lapply(data,function(x) x %in% c(-99,-999)))
> data[!ind,]
    a  b
1 100 23
3 322 25
4 155 25
like image 42
joran Avatar answered Sep 15 '25 01:09

joran