如何使用列表中的字符串值对数据框进行子集化? [英] How to subset dataframe using string values from a list?

查看:56
本文介绍了如何使用列表中的字符串值对数据框进行子集化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆