[R] The most straightfoward way to write a function that sums over the rows of a matrix

David Winsemius dwinsemius at comcast.net
Tue Jun 16 17:31:26 CEST 2009


The apply function is the way to iterate over rows or columns of  
dataframes or matrices. An example would have made this process easier  
testing and I have given up doing that job for

You might try:

apply(observs, 1, function(x)  Fn(par, x) )

On Jun 16, 2009, at 11:08 AM, Stu @ AGS wrote:

> Hello!
>
>
>
> I am trying to write a function with vector and data.frame  
> parameters that
> uses the sum() function and values from the rows of the data.frame.
>
> I need to pass this function as a parameter to optim().
>
>
>
> My starting point is:
>
> observs <- data.frame(y, x1, x2, x3)
>
>
>
> Fn <- function(par, observs) {
>
>                sum( (y - (par[1] * (x1 + 1) * x2^(-par[2]) *  
> x3^par[3])^2 )
>
> }
>
>
>
> y, x1, x2, x3 are all vectors.
>
>
>
> I am a bit new to R and I have not been able to find a good  
> description of
> how to iterate over rows in a data.frame.
>
>
>
> What is a straightforward way to do this?
>
> What am I missing?
>
>
>
> Thanks
>
> Stu
>
>
>
>
> 	[[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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list