Home > Blockchain >  Find a vector given certain criteria in R
Find a vector given certain criteria in R

Time:10-17

I was searching online if it is possible to create a vector given certain conditions, such as it must contain 2 and 6 but not 5 and 1, also that it is in a specific range (2 000 000-4 999 999), and also that it must be even. I have genuinely no idea about how to give these commands to R even if I know the basic functions to create a vector.

Thanks in advance for your time and for the big help

CodePudding user response:

You can try the code below

# create a sequence from 2000000 to 4999999
v <- 2e6:(5e6 - 1) 

# filter the sequence with given criteria
v[grepl("(2.*6)|(6.*2)", v) & !grepl("(1.*5)|(5.*1)", v)]

CodePudding user response:

You can create it using "seq" function.

seq(from = 2, to = 7, by = 2) 
#> [1] 2 4 6

Then use "setdiff" function to remove specific values you dont need.

remove <- c(2)

#> a
 [1] 2 4 6
#> setdiff(a, remove)
[1] 4 6
  • Related