ModalBro
ModalBro

Reputation: 554

Pattern matching only the first number in a string in R

I have a dataframe with a series of six-digit numbers that correspond to bill ID's. The ID's that start with odd numbers correspond to house votes and the ones with even numbers correspond to senate votes. For example, my variable would look like this:

var <- runif(20, 100000, 999999) 

I am stuck on trying to figure out a grep() code that I can use with the subset() command to separate the values that start with even numbers and those that start with odd numbers. Does anyone have any suggestions? Thank you!

Upvotes: 0

Views: 353

Answers (3)

alex
alex

Reputation: 345

var <- runif(20, 100000, 999999) 
odds <- substr(var,1,1) %in% c("1", "3", "5", "7", "9")
evens <- substr(var,1,1) %in% c("2", "4", "6", "8")

var[odds]
var[evens]

Or if it is a data frame:

df <- data.frame(var = runif(20, 100000, 999999), 
                 outcome = rbinom(20, 1, .5)
                 )

odds <- df[substr(df$var,1,1) %in% c("1", "3", "5", "7", "9"),]
evens <- df[substr(df$var,1,1) %in% c("2", "4", "6", "8"),]

Upvotes: 1

Matthew Plourde
Matthew Plourde

Reputation: 44614

You can also use is.even <- grepl('^[02468]', var)

Upvotes: 6

Jens Tierling
Jens Tierling

Reputation: 701

evenNo   <- subset(var, trunc(var*1e-5) %% 2 == 0)

unevenNo <- subset(var, trunc(var*1e-5) %% 2 == 1)

Upvotes: 1

Related Questions