R:应用、自定义函数和数据框名称 [英] R: Apply, custom function and Dataframe names

查看:21
本文介绍了R:应用、自定义函数和数据框名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 Indices 包含对应于数据框的各种名称(ie 一个名称 "Index 1" 有一个对应的数据框架 Index 1).

I have a data frame Indices containing various names which correspond to data frames (i.e. a name "Index 1" has a corresponding data frame Index 1).

现在我想在所有数据框上运行我的自定义函数 calcScores 并向该数据框添加几列.因为我不在全局环境中,所以我返回那个新"数据框并想将它分配回原始变量 Index 1,所以 Index 1 现在有带有添加列的新数据框.

Now I want to run my custom function calcScores over all data frames and add several columns to that data frame. Since I'm not in the global environment I return that "new" data frame and want to assign it back to the original variable Index 1, so Index 1 now has the new data frame with the added columns.

这是我的代码(因为所有数据都是非常自定义的,所以我不可能使这个 100% 可重现,但我希望你理解我的问题).

Here's my code (no chance I can make this 100% reproducible since all data is very custom but I hope you understand my question).

# 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 给出以下错误:

I guess my problems are in the apply and with the whole get, assign and gsub story. The scoping is here obviously the issue... At the moment apply gives the following error:

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

推荐答案

好的解决了...抱歉发帖.这就是解决方案:envir = .GlobalEnv

Ok solved it...sorry for the post. That is the solution: envir = .GlobalEnv

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

这篇关于R:应用、自定义函数和数据框名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆