Richa
Richa

Reputation: 59

How to subset dataframe using string values from a list?

I have a data.frame with several variables for a universe of stocks and I want to create a subset of this data frame that filters the data I have for just the S&P 500 stocks.

I created a list of all the stocks in the S&P 500, and I basically want the program to go through my data frame and copy over all the rows which contain an item from my S&P 500 list. I tried using a for-loop and that crashed my RStudio, so if anyone knows if there's a way I can do this, please let me know!

This code works for just one stock in the S&P500, but I want it to work for all of them. t is what I named my data frame.

sp500dataonly <- filter(t, SYMBOL == "AAPL")

All help is greatly appreciated!

Upvotes: 2

Views: 4682

Answers (1)

Bryan Goggin
Bryan Goggin

Reputation: 2489

Say you have a set (technically not a list in R. It is actually a vector.) of the stocks you want to include called myStocks

Then you can subset by saying:

sp500dataonly<- t[t$SYMBOL %in% myStocks,]

example:

mySpecies <-c("versicolor","virginica" )

iris[iris$Species %in% mySpecies,]

Will give the subset we are after.

Upvotes: 3

Related Questions