2013-10-07 35 views
0

我有一個數據幀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,並與整個getassigngsub故事。在這裏的範圍顯然是問題...在此刻申請給出了以下錯誤:

Error: unexpected symbol in: 
"apply(Indices,1,function(x) assign(gsub(" ","",x,fixed=TRUE), calcScores(get(gsub(" ","",x,fixed=TRUE)),lookback_window)) 
apply" 
+1

只是一個提示。當你創建一個名爲'Index 1'的變量時,你應該將它們存儲在一個列表中。另外,你真的在​​變量名中包含空格嗎?這聽起來像個壞主意。 – Backlin

回答

1

好的解決了它......抱歉的帖子。這是解決方案:ENVIR = .GlobalEnv

apply(Indices,1,function(x) assign(gsub(" ","",x,fixed=TRUE), calcScores(get(gsub(" ","",x,fixed=TRUE)),lookback_window),envir = .GlobalEnv)) 
0

你爲什麼不只是使用for循環,這將與範圍界定問題的幫助?像這樣的:

mydf1 <- data.frame(x=1:3, y=2:4) 
mydf2 <- data.frame(x=3:5, y=4:6) 

indices <- c("mydf1","mydf2") 

for (dfname in indices) { 
    result <- get(dfname) 
    result$z <- result$x+ result$y 
    assign(dfname, result) 
} 
+0

我認爲比申請慢?我以爲我讀過一次... – MichiZH

+0

@MichiZH使用'for'循環代替矢量化函數會更慢。但是在這裏,我認爲這並沒有什麼區別,因爲你只是一次遍歷列表。 – juba

0

看起來像你想通過股票分割你的數據和應用每個分裂元素的功能。

這是byddplyplyr包的工作。

by(df,df$ticker,FUN=calcScores,LookbackWindow=lookback_window)