1
data <- c("Demand =  001   979", "Demand =  -08   976 (154)", "Demand =  -01   975 (359)")
data <- str_match(data, pattern = ("Demand = (.*) (.*)"))

I need to extract the first 2 sets of numbers (including the - sign) into columns using str_match.
Exclude 3rd set of numbers in bracket ().
Any help is welcomed.

Output:

## [1] "001" "-08" "-01"
## [2] "979" "976" "975"

2 Answers 2

1

How about removing everything else?

data <- c("Demand = 001 979", "Demand = -08 976 (154)", "Demand = -01 975 (359)")
data <- gsub("Demand = ", "", x = data)
data <- trimws(gsub("\\(.*\\)", "", x = data))

out <- list()

out[[1]] <- sapply(data, "[", 1)
out[[2]] <- sapply(data, "[", 2)
out

[[1]]
[1] "001" "-08" "-01"

[[2]]
[1] "979" "976" "975"
Sign up to request clarification or add additional context in comments.

Comments

0

A possibility with str_extract_all() from stringr:

sapply(str_extract_all(x, "-?[0-9]+?[0-9]*"), function(x) x[1])

[1] "001" "-08" "-01"

sapply(str_extract_all(x, "-?[0-9]+?[0-9]*"), function(x) x[2])

[1] "979" "976" "975"

Or using the idea of @Roman Luštrik with strsplit():

sapply(strsplit(gsub("Demand = ", "", x), " "), function(x) x[1])

[1] "001" "-08" "-01"

1 Comment

Meh, I tried fetching all integer and a minus sign within the square brackets and failed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.