How to grab some character after "-"?

Viewed 55

Suppose I have an "option code" column in my tbl, the data is like this:

m1803-C-2550
m1807-P-3050

I want to grab C/P between "-" as my new variable "option type", and 2550/3050 after the second "-" as my new variable "strike price".

How do I code with tidyverse?

Now, I could solve the first question by

tbl %>% mutate(option_type = str_sub(option_code, str_locate(option_code, "[CP]"))

But I could not solve my second question, or you guys may have an elegant way to solve my first question.

4 Answers

You can use separate() in tidyr to split strings by a separator.

library(tidyr)

df %>%
  separate(option_code, c(NA, "option_type", "strike_price"))

#   option_type strike_price
# 1           C         2550
# 2           P         3050
  • NA means to drop the first part, i.e. m1803.
  • If you want to keep option_code, then just add the argument remove = F.

Data

df <- data.frame(option_code = c("m1803-C-2550", "m1807-P-3050"))

You can use str_extractfrom stringr:

df %>% mutate(option_type = str_extract(option_code, "[CP]"),
              strike_price = str_extract(option_code, "(?<=[CP]-)\\d+"))

# A tibble: 2 x 3
  option_code  option_type strike_price
  <chr>        <chr>       <chr>       
1 m1803-C-2550 C           2550        
2 m1807-P-3050 P           3050  

Data:

df <- tibble(option_code = c("m1803-C-2550","m1807-P-3050"))

Try this:

library(dplyr)
library(stringr)

  df %>% 
  mutate(option_type = str_extract(option_code, "(?<=-)[CP]"),
         strike_price = as.numeric(str_extract(option_code, "(?<=-)\\d+")))

#>    option_code option_type strike_price
#> 1 m1803-C-2550           C         2550
#> 2 m1807-P-3050           P         3050

data

df <- data.frame(option_code =  c("m1803-C-2550", "m1807-P-3050"))

Created on 2020-05-23 by the reprex package (v0.3.0)

Base R solution:

setNames(data.frame(lapply(strsplit(tmp, "-"),"[", -1)), c("option_type", "strike_price"))

Data:

tmp <- c("m1803-C-2550",
         "m1807-P-3050")
Related