[R] using lapply to get function values

David Winsemius dwinsemius at comcast.net
Fri Jan 10 10:46:34 CET 2014


On Jan 10, 2014, at 2:04 AM, Long Vo wrote:

> Hi R users,
> I need to apply a function on a list of vectors. This is simple when  
> I use
> functions that returns only one numerical value such as 'mean' or
> 'variance'. Things get complex when I use functions returning a list  
> of
> value, such as 'acf'.
> In the following example I first create a list of vectors with equal  
> length
> 10.  Then I try to get the first order autocorrelation coefficient  
> of each
> vector using lapply:
>
> #####
> library(stats)
> X=rnorm(1:100)
> Y=split(X,as.numeric(gl(length(X),10,length(X))))# to divide X into 10
> sub-vectors
> app=lapply(Y,FUN=acf,lag.max=1,plot=F)
> app
> #####
>
> I need to know how to display other values of the function e.g.  
> 'type',
> 'lag' not just 'acf'. Because using
> ####
> app=lapply(Y,FUN=acf$type,lag.max=1,plot=F)
> ####
>

acf$type is not a function. The "$" function is a wrapper for "[[" so  
try:

lapply(app, "[[", 'type')

To do it in one step, try:

lapply(Y, function(x) acf(x)$type)

-- 
David.

> prompts the error "object of type 'closure' is not subsettable"
>
>
> Note that this is only an illustrative example. The function I am  
> studying
> is not 'acf', but it also return a list of values and I need to call  
> out
> specific values.
>
> Helps and comments are welcome.
>
> Long
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/using-lapply-to-get-function-values-tp4683373.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list