[R] Select only rows that don't contain one number

arun smartpink111 at yahoo.com
Tue Jul 30 16:40:56 CEST 2013


You could also use:
indx<-with(x,(1+2*(a!=-1)+4*(b!=-1)+8*(c!=-1)+16*(d!=-1)+32*(e!=-1)))
 x[indx==max(indx),]
#  a b c d e
#3 2 3 3 4 3
#5 4 5 5 6 4


#Speed comparisons:
set.seed(548)
x1<- as.data.frame(matrix(sample(c(-1,1:10),5*1e6,replace=TRUE),ncol=5))

system.time({
 index <- apply(x1, 1, function (x) { !(c(-1) %in% x)})
 res1<-x1[index, ]
})
# user  system elapsed 
# 11.252   0.028  11.304 

system.time({res2<- x1[rowSums(!x1==-1)==ncol(x1),]})
# user  system elapsed 
#  0.340   0.004   0.342 
identical(res1,res2)
#[1] TRUE

system.time({
indx<-with(x1,(1+2*(V1!=-1)+4*(V2!=-1)+8*(V3!=-1)+16*(V4!=-1)+32*(V5!=-1)))
res3<-x1[indx==max(indx),]
})
#  user  system elapsed 
#  0.268   0.008   0.274 
 identical(res1,res3)
#[1] TRUE
A.K.




----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: Dimitri Liakhovitski <dimitri.liakhovitski at gmail.com>
Cc: R help <r-help at r-project.org>
Sent: Tuesday, July 30, 2013 10:30 AM
Subject: Re: [R] Select only rows that don't contain one number

x[rowSums(!x<0)==ncol(x),] #if you don't want x<0
#  a b c d e
#3 2 3 3 4 3
#5 4 5 5 6 4

#or
 x[rowSums(!x==-1)==ncol(x),]
#  a b c d e
#3 2 3 3 4 3
#5 4 5 5 6 4


A.K.




----- Original Message -----
From: Dimitri Liakhovitski <dimitri.liakhovitski at gmail.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Tuesday, July 30, 2013 10:06 AM
Subject: [R] Select only rows that don't contain one number

Hello!

I have a data frame:

x<-data.frame(a=c(-1,1,2,3,4),b=c(1,-1,3,4,5),c=1:5,d=2:6,e=c(1,2,3,-1,4))
x

How can I grab only those rows that don't contain any -1s (no matter in
what columns? Without writing a loop.
In other words, I want my output to contain only rows 3 and 5 of x.

Thank you very much!

    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list