r - How do I calculate a percent change of a zoo object using sapply? -


i have list of zoo objects. core data adjusted close of several stock symbols, monthly data. each list object separate time series each ticker. i'd calculate monthly change each month, in each object. if helps, here's gets me desired calculation:

path = 'c:/sectorrotationsymblist072013.csv' symbs = read.csv(path, header = false, stringsasfactors = false) symbs = symbs[, 1] importdata = vector('list', length(symbs))  #get monthly pricing data. (sidx in 1:length(symbs)){     #import data each symbol list.     importdata[[sidx]] = get.hist.quote(instrument= symbs[sidx],         start="2000-01-01", end="2013-07-15", quote="adjclose",         provider="yahoo", origin="1970-01-01",         compression="m", retclass="zoo") }  names(importdata) = symbs 

i can month on month change each object using sapply follows:

monthlygainslosses = sapply(importdata, diff) 

i want relative change, though (%). i've tried every variation can think of on simple calculation, including:

monthlygainslosses = sapply(importdata, diff / importdata) monthlygainslosses = sapply(importdata, diff / coredata(importdata)) 

none of work. latter (which seems logical me) error:

non- numeric argument binary operator. can help?

sapply expects function second argument , diff / coredate(importdata) not function in r expression.

you can supply lambda correct it.

monthlygainslosses = sapply(importdata, function(x) diff(x) / (x)) 

or if want avoid lambda, in 2 steps.

perc <- function(x) diff(x) / x monthlygainslosses = sapply(importdata, perc) 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -