How to subset dataframe using string values from a list?

筅森魡賤 提交于 2019-12-12 03:44:12

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/37635085/how-to-subset-dataframe-using-string-values-from-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!