使用向量作为新变量的输入 [英] Using vectors as inputs in new variables

查看:99
本文介绍了使用向量作为新变量的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框是SPData,其中包括过去25年(每年约250天)的S& P500的日期,开盘价,收盘价和交易量. 另外,我有SPData$Year,它只是一个向量,其日期列中的年份以数字形式存储了1990年至2015年.

My data frame is SPData, which includes date, open price, closing price and volume for the S&P500 for the last 25 years (~ 250 days per year). Additionally, I have SPData$Year, which is simply a vector with the year from the date column stored numerically, from 1990 - 2015.

library(dplyr)
SPData1990 <- filter(SPData, Year == 1990)

得到一个约有250个观测值的数据框,在1990年的每个交易日都有一个观测值.我已经进行了25年.

results in a data frame with ~250 observations, one for each trading day in 1990. I did this for all 25 years already.

是否可以创建一个公式,将每年对应的所有其他数据另存为新的数据框(SPData1991,SPData 1992,SPData1993等)?我试图通过一个与公式years <- unique(SPData$Year, FALSE)对应的for(i年)循环来思考,但是我对编程一般还不熟悉,无法弄清楚这一点.

Is there a way to create a formula that would save all the other data corresponding from each year as a new data frame (SPData1991, SPData 1992, SPData1993, etc.)? I was trying to think through a for(i in years) loop corresponding to the formula, years <- unique(SPData$Year, FALSE), but I am not familiar enough with programming in general to figure this out.

谢谢

推荐答案

感谢@ user20650 ...

With thanks to @user20650...

# reproducible example!
set.seed(123)
year_range = 1990:2014
SPData <- data.frame(Year=sample(year_range,1000,replace=TRUE),
                     Sales=runif(1000,min=100,max=200) )

# split the list into data frames on "SPDataYYYY" and store in global environment
list2env(split(SPData, paste0("SPData",SPData$Year)),
         envir = .GlobalEnv)
ls()
# [1] "SPData"     "SPData1990" "SPData1991" "SPData1992" "SPData1993" "SPData1994"
# [7] "SPData1995" "SPData1996" "SPData1997" "SPData1998" "SPData1999" "SPData2000"
# [13] "SPData2001" "SPData2002" "SPData2003" "SPData2004" "SPData2005" "SPData2006"
# [19] "SPData2007" "SPData2008" "SPData2009" "SPData2010" "SPData2011" "SPData2012"
# [25] "SPData2013" "SPData2014" "year_range"

这篇关于使用向量作为新变量的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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