SDahm
SDahm

Reputation: 436

Use of extract in pipe: select numbers and put them into separate variables

I have a data.frame. One variable contains values like those c('Test11','Test12','Test21','Test22'). I would like to make two new variables out of this. Var1 including the first number. Var2 including the second number.

Something like: data_Test %>% extract(Phase, c('Test','Order'), regex = "(.[[:digit:]])-([[:digit:]])" )

I know it is simple question. But i am not very familiar with regex. All those ./:[ and so on...

Upvotes: 0

Views: 32

Answers (2)

prosoitos
prosoitos

Reputation: 7347

data_Test$Var1 <- gsub("Test(\\d)\\d", "\\1", data_Test$Phase)

data_Test$Var2 <- gsub("Test\\d(\\d)", "\\1", data_Test$Phase)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521178

You may try using sub here for a base R option:

x <- c("Test11", "Test12", "Test21", "Test22")
out <- sub("^\\D+", "", x)
out

[1] "11" "12" "21" "22"

Upvotes: 0

Related Questions