我有一個數據幀Indices
對應於數據幀(即一個名稱"Index 1"
具有相應數據幀Index 1
)含有各種名稱。R:應用,定製功能和數據幀名稱
現在我想在所有數據框上運行自定義函數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
故事。在這裏的範圍顯然是問題...在此刻申請給出了以下錯誤:
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'的變量時,你應該將它們存儲在一個列表中。另外,你真的在變量名中包含空格嗎?這聽起來像個壞主意。 – Backlin