【发布时间】:2013-10-07 13:32:19
【问题描述】:
我有一个数据框Indices,其中包含与数据框相对应的各种名称(即名称"Index 1"有一个对应的数据框Index 1)。
现在我想在所有数据框上运行我的自定义函数calcScores 并向该数据框添加几列。由于我不在全局环境中,因此我返回了那个“新”数据框并希望将其分配回原始变量 Index 1,因此 Index 1 现在有了带有添加列的新数据框。
这是我的代码(我不可能做到 100% 可重现,因为所有数据都是非常自定义的,但我希望你能理解我的问题)。
# Here the unique Index names are derived and stored
# Problem is the index names are stored as "Index 1", "Index 2" etc.
# Thats why I have to adjust These #titles and create individual data Frames
Indices <- unique(df[1])
apply(unique(df[1]), 1, function(x){
assign(gsub(" ","",x,fixed=TRUE), subset(df,ticker==x), envir = .GlobalEnv)
})
calcRollingAverage <- function(Parameter, LookbackWindow){
Output <- rollapply(Parameter, LookbackWindow, mean, fill=NA, partial=FALSE,
align="right")
}
calcScores<-function(Index, LookbackWindow){
Index$PE_Avg = calcRollingAverage(Index$PE_Ratio, LookbackWindow)
Index$PE_DIV_Avg = Index$PE_Ratio/Index$PE_Avg
Index$PE_Score = cut(Index$PE_DIV_Avg, breaks=PE_Breaks, labels=Grades)
return(Index)
}
apply(Indices,1,function(x) assign(gsub(" ","",x,fixed=TRUE), calcScores(get(gsub(" ","",x,fixed=TRUE)),lookback_window)))
我想我的问题在于apply 以及整个get、assign 和gsub 故事。范围界定显然是问题所在......目前 apply 给出以下错误:
Error: unexpected symbol in:
"apply(Indices,1,function(x) assign(gsub(" ","",x,fixed=TRUE), calcScores(get(gsub(" ","",x,fixed=TRUE)),lookback_window))
apply"
【问题讨论】:
-
只是小费。当您创建名为
Index 1等的变量时,您可能应该将它们存储在一个列表中。另外,你真的在变量名中包含空格吗?这听起来是个坏主意。