1

Below is the final line of code that creates the stock options dataframe screenshot below. It's not ideal, but because of the nature of the code and the api it uses, I think this is the easiest way to supplement my question.

What I want to do is create a new column that is just the ticker symbol. For example all of the stock options for Tesla would have a separate column that is just "TSLA". And all of the Apple stock options would have a separate column that is just "AAPL". So most rows would have the same value. I would imagine there is a way to take the first word from the "SYMBOL" column before the "_" or the first word from the "DESCRIPTION" column before the space and put that value in a new column.

call.option.dataframe = do.call(rbind, options.chain.datalist)

dataframe screenshot

Blockquote

3
  • 1
    You could use something like df$NEW_SYMBOL <- gsub("(\\w+)_\\w+", "\\1", df$SYMBOL). Commented Aug 4, 2021 at 18:03
  • This works except for the rows in which the strike price has a .5 in it. For example in row 68, the symbol and description column has 692.5. The NEW_SYMBOL column will return TSLA.5 instead of TSLA. Commented Aug 4, 2021 at 18:13
  • 1
    Well... try gsub("([A-z]+)_.*", "\\1", df$SYMBOL) Commented Aug 4, 2021 at 18:18

1 Answer 1

4

We could use separate from tidyr package. Below code creates in dataframe df additional two columns out of column SYMBOL -> A and B separated by _.

library(tidyr)
library(dplyr)

df %>% 
    separate(SYMBOL,c("A", "B"), sep = "_", remove = FALSE)
Sign up to request clarification or add additional context in comments.

Comments

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.