[R] lapply - value changes as parameters to function?
Phil Spector
spector at stat.berkeley.edu
Fri Sep 18 19:16:52 CEST 2009
Mark -
The "l" in lapply refers to that fact that it will *return*
a list, not that it wants a list for input. You could input
a list, but then each element of the list would be one of the
values you wanted processed. So I think you want
x = seq(5:20)
ResultList = lapply(x, DoAvgCalcs, IndexData, Lookback=x,
SampleSize=TestSamples , Iterations=TestIterations )
This will return a list whose elements are the result of calling
the DoAvgCalcs function with each value contained in x. If they
were all the same length, and you wanted them simplified to a matrix,
you could use sapply (s for simplify) instead of lapply (l for list).
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Fri, 18 Sep 2009, Mark Knecht wrote:
> Hi,
> I'm trying to get better at things like lapply but it still stumps
> me. I have a function I've written, tested and debugged using
> individual calls to the function, ala:
>
> ResultList5 = DoAvgCalcs(IndexData, Lookback=5,
> SampleSize=TestSamples , Iterations=TestIterations )
> ResultList8 = DoAvgCalcs(IndexData, Lookback=8,
> SampleSize=TestSamples , Iterations=TestIterations )
> ResultList13 = DoAvgCalcs(IndexData, Lookback=13,
> SampleSize=TestSamples , Iterations=TestIterations )
> ResultList21 = DoAvgCalcs(IndexData, Lookback=21,
> SampleSize=TestSamples , Iterations=TestIterations )
>
> The function returns a list of numbers which I use for processing
> later. I'd like to run this on a longer list (100's of values for
> Lookback) so my thought was to try lapply but so far I cannot get the
> darn thing right.
>
> Let's say I want to run the function on a string of values:
>
> BarTestList = list(seq(5:20))
>
> So my thought was something like:
>
> x = list(seq(5:20))
> ResultList = lapply(x, DoAvgCalcs, IndexData, Lookback=x,
> SampleSize=TestSamples , Iterations=TestIterations )
>
> which fails down lower complaining that what it's receiving for
> Lookback isn't an integer:
>
>> x = list(seq(5:20))
>> ResultList = lapply(x, DoAvgCalcs, IndexData, Lookback=x, SampleSize=TestSamples , Iterations=TestIterations )
> Error in MyLag(df$Close, Lookback) :
> (list) object cannot be coerced to type 'integer'
>>
>
> Can someone suggest how to do this correctly?
>
> Thanks,
> Mark
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list