r - Selecting the pairs of numbers in a vector which difference is equal to a predetermined value -


i have vector of numbers select pairs 2 units apart. if have vector p defined follows:

p<-c(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47) 

i select following pairs:

3,5; 5,7; 11,13; 17,19; 29,31; 41,43 

i tried unsuccessfully select @ least these numbers in vector

j<-null for(i in seq(p)) if (p[i+1]-p[i]==2) j<-c(j,i,i+1) 

but not give desired output. help.

there better way this, here idea expand.grid,

df <- expand.grid(p, p) unname(apply(df[df[,1]-df[,2] == -2,], 1,paste, collapse = ',')) #[1] "3,5"   "5,7"   "11,13" "17,19" "29,31" "41,43" 

if want data frame simply,

df[df[,1]-df[,2] == 2,] #    var1 var2 #18     5    3 #34     7    5 #66    13   11 #98    19   17 #146   31   29 #194   43   41 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -