[R] apply a function separately on each element of a list

Rui Barradas ruipbarradas at sapo.pt
Fri Aug 24 19:20:05 CEST 2012


Hello,

Your example doesn't run, lmList needs a 'data' argument.

set.seed(8109)
d <- rep(1:10, each=10)
x <- rnorm(100)
e <- rnorm(100)
y <- 2*x + e

dat <- data.frame(x=x, y=y, d=d, e=e)

model <- lmList(y ~ x | d, data = dat)
predict(model)

To the op: if you already have the larger data.farme divided into a list 
of smaller df's, such as the 'lst' below, you can use lapply.


df.lst <- split(dat, dat$d)


model.lst <- lapply(df.lst, function(.data) lm(y ~ x, data = .data))
lapply(model.lst, coef)  # just an example
lapply(model.lst, predict)  # what you want

Hope this helps,

Rui Barradas

Em 24-08-2012 16:05, Daniel Malter escreveu:
> The easiest way may be to use lmList in the nlme library:
>
> #simulate data
> d<-rep(1:10,each=10)
> x<-rnorm(100)
> e<-rnorm(100)
> y<-2*x+e
>
> require(nlme) #or install and load package
>
> lmList(y~x|d)
>
> #predicted values are obtained with:
>
> predict(lmList(y~x|d)
>
> HTH,
> Daniel
>
>
>
>
>
> jeff6868 wrote
>> Hi everybody,
>>
>> I have a question about applying a specific function (with the
>> calculations I want to do), on a list of elements.
>>
>> Each elements are like a data.frame (with nrows and ncolumns), and have
>> the same structure.
>> At frist, I had a big data.frame that I splitted in all my elements of my
>> list. They have been splitted by day.
>> For example, the name of the first element of my list is "2011-01-01", and
>> is a data.frame corresponding to all my data from this specific date. Then
>> my second element is "2011-01-02", etc....
>>
>> My question is: how can I apply a function on each element separately (a
>> bit like a loop)?
>>
>> For example, if my data from the first element "2011-01-01" is:
>> element1 <- data.frame(x=rnorm(1:10),data=c(1:10))
>>
>> I would like to do a regression between "x" and "data (so lm(data ~x) ),
>> to get the predicted values of the regression, and then to keep the
>> results in a new object.
>>
>> And then, do the same with the second element (regression between "x" and
>> "data" of the second element), keep the results of the predicted values
>> and keep the results.
>>
>> ... and so one with 200 elements.
>>
>> Is there any way to do this?
>>
>> Thanks a lot!
>>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/apply-a-function-separately-on-each-element-of-a-list-tp4641186p4641204.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.




More information about the R-help mailing list