[R] Applying function to all elements of a formula

Dennis Murphy djmuser at gmail.com
Sat Jun 18 12:07:42 CEST 2011


Much better..nice!

Dennis

On Sat, Jun 18, 2011 at 1:53 AM, Dimitris Rizopoulos
<d.rizopoulos at erasmusmc.nl> wrote:
> maybe another way is by reconstructing the formula using paste(), e.g.,
>
> data <- data.frame(y = rnorm(5), x1 = runif(5),
>    z = runif(5), age = runif(5))
>
> nameRsp <- "y"
> nams <- names(data)
> namsX <- nams[!nams %in% nameRsp]
> form <- as.formula(paste(nameRsp, "~" ,
>    paste("log(", namsX, ")", sep = "", collapse = "+")))
>
> lm(form, data)
>
>
> I hope it helps.
>
> Best,
> Dimitris
>
>
> On 6/18/2011 10:41 AM, Dennis Murphy wrote:
>>
>> Yes, it's possible, but if you want to do prediction on future
>> x-values, you will likely have a problem.
>>
>> One way to do it would be something like (assuming y is the first column
>> of dat)
>>
>> reg<- lm(y ~ log(as.matrix(dat[, -1])), dat)
>>
>> but the output would be pretty ugly (see summary(reg)). Another would
>> be to construct the matrix outside the data frame and do something
>> like
>>
>> X<- log(as.matrix(dat[, -1]))
>> reg<- lm(dat$y ~ X)
>>
>> There may be better ways, though...
>>
>> Dennis
>>
>> On Fri, Jun 17, 2011 at 11:08 PM, Scott Fortmann-Roe<scottfr at gmail.com>
>>  wrote:
>>>
>>> Hi,
>>>
>>> I would like to do a regression like:
>>>
>>>         reg<- lm(y~log(.), data)
>>>
>>> where the log function is applied to "." in the form:
>>>
>>>        log(x1)+ log(x2)+ log(x3)...
>>>
>>> instead of in the form
>>>
>>>       log(x1+x2+x3+...)
>>>
>>>
>>> Is this possible?
>>>
>>> Thank you,
>>> Scott
>>>
>>>        [[alternative HTML version deleted]]
>>>
>>> ______________________________________________
>>> 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.
>>>
>>
>> ______________________________________________
>> 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.
>>
>
> --
> Dimitris Rizopoulos
> Assistant Professor
> Department of Biostatistics
> Erasmus University Medical Center
>
> Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
> Tel: +31/(0)10/7043478
> Fax: +31/(0)10/7043014
> Web: http://www.erasmusmc.nl/biostatistiek/
>



More information about the R-help mailing list