scope - R: Apply, custom function and Dataframe names -
i have data frame indices
containing various names correspond data frames (i.e. name "index 1"
has corresponding data frame index 1
).
now want run custom function calcscores
on data frames , add several columns data frame. since i'm not in global environment return "new" data frame , want assign original variable index 1
, index 1
has new data frame added columns.
here's code (no chance can make 100% reproducible since data custom hope understand question).
# here unique index names derived , stored # problem index names stored "index 1", "index 2" etc. # thats why have adjust these #titles , 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)))
i guess problems in apply
, whole get
, assign
, gsub
story. scoping here issue... @ moment apply gives 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"
ok solved it...sorry post. solution: envir = .globalenv
apply(indices,1,function(x) assign(gsub(" ","",x,fixed=true), calcscores(get(gsub(" ","",x,fixed=true)),lookback_window),envir = .globalenv))
Comments
Post a Comment