How to subset dataframe using string values from a

2019-09-02 17:24发布

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!

标签: r list subset
1条回答
\"骚年 ilove
2楼-- · 2019-09-02 17:32

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.

查看更多
登录 后发表回答