如何使用列表中的字符串值对数据框进行子集化? [英] How to subset dataframe using string values from a list?
问题描述
我有一个data.frame
,其中有多个变量适用于整个股票市场,我想创建此数据框的子集,以过滤仅用于标准普尔500股票的数据.
我创建了标准普尔500指数中所有股票的列表,基本上,我希望该程序遍历数据框并复制包含标准普尔500清单中某项的所有行.我尝试使用for循环,这使我的RStudio崩溃了,所以如果有人知道我是否有办法做到这一点,请告诉我!
此代码仅适用于S&P500的一只股票,但我希望它适用于所有股票.这就是我命名的数据框.
sp500dataonly <- filter(t, SYMBOL == "AAPL")
非常感谢所有帮助!
假设您要设置的一组股票(在技术上不是R中的列表.它实际上是向量). >
然后,您可以通过说出以下内容来进行分组:
sp500dataonly<- t[t$SYMBOL %in% myStocks,]
示例:
mySpecies <-c("versicolor","virginica" )
iris[iris$Species %in% mySpecies,]
将给出我们需要的子集.
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!
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.
这篇关于如何使用列表中的字符串值对数据框进行子集化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!