R:应用,自定义函数和数据框名称

时间:2013-10-07 13:32:20

标签: r scope apply

我有一个数据框Indices,其中包含与数据框对应的各种名称(名称"Index 1"具有相应的数据框Index 1)。< / p>

现在,我想在所有数据框上运行自定义函数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的故事中。范围界定显然是问题......目前,apply会出现以下错误:

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

3 个答案:

答案 0 :(得分:1)

好的解决了...对不起该帖子。这就是解决方案: envir = .GlobalEnv

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

答案 1 :(得分: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)
}

答案 2 :(得分:0)

您希望通过自动收报机拆分数据并在每个拆分元素上应用函数。

这是byddply plyr包中的作业。

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