0

我有一个数据框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和故事。范围界定显然是问题所在......目前 apply 给出以下错误:assigngsub

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

3 回答 3

1

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

apply(Indices,1,function(x) assign(gsub(" ","",x,fixed=TRUE), calcScores(get(gsub(" ","",x,fixed=TRUE)),lookback_window),envir = .GlobalEnv))
于 2013-10-07T13:40:47.480 回答
0

Looks like you want to split your data by ticker and apply a function on each splitted element.

This is a job for by or ddply in plyr package.

by(df,df$ticker,FUN=calcScores,LookbackWindow=lookback_window)
于 2013-10-07T13:50:30.793 回答
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)
}
于 2013-10-07T13:41:13.820 回答