JackW24
JackW24

Reputation: 135

How to make new column values based on part of string from another column in R

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

Upvotes: 1

Views: 2526

Answers (1)

TarJae
TarJae

Reputation: 78927

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)

Upvotes: 4

Related Questions