[R] function inside a function

Berend Hasselman bhh at xs4all.nl
Thu Dec 12 19:35:58 CET 2013


On 12-12-2013, at 17:10, eliza botto <eliza_botto at hotmail.com> wrote:

> Dear users of R,
> I am trying to inculcate a function inside a function. For that to be done, i copied following function from internet. 
> 
> library(nleqslv) fun <- function(x) { 
>     f <- numeric(length(x)) 
>     f[1] <-  A[,1]+x[2] - 1/x[1] 
>     f[2] <-  A[,2]+x[2] - sin(x[1]) 
>     f 
> } 
> x.start <- c(1,1) 
> nleqslv(x.start,fun) 
> I have a matrix "A" with dimension 124 rows and 2 columns. In f[1] line, in place of A[,1] i want to inculcate each value (each row) of 
> column 1 of matrix A. while doing it, In f[2] line, in place of A[,2] i want to inculcate each value (each row) of column 2 of matrix A.  
> For suppose A has following rows
> 0.6772941                              0.5962983
> 0.4348938                              0.4563702
> 0.4481236                              0.4418828
> 0.4213013                              0.3944993
> 0.4682232                              0.4485623
> 0.4798529                              0.4477387
> 0.7029005                              0.5533228
> While using 0.66772941 in f[1], use 0.5962983 in f[2]. 
> How can i do this in R.
> Thanks in advance,


It is not clear what you actually want. 
Maybe something like this

library(nleqslv)

A <- matrix(c(0.6772941,  0.5962983,
              0.4348938,  0.4563702,
              0.4481236,  0.4418828,
              0.4213013,  0.3944993,
              0.4682232,  0.4485623,
              0.4798529,  0.4477387,
              0.7029005,  0.5533228), byrow=TRUE,ncol=2)

fun <- function(x, krow) {
    f <- numeric(length(x))
    f[1] <- A[krow,1] + x[2]- 1/x[1]
    f[2] <- A[krow,2] +x[2] - sin(x[1])
    f
}

x.start <- c(1,1)
nleqslv(x.start, fun, krow=1)
nleqslv(x.start, fun, krow=2)


> Eliza 		 	   		  
> 	[[alternative HTML version deleted]]
> 

Please do not post in HTML. You should know by now.

Berend

> ______________________________________________
> 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