If you want to assign to a variable in your workspace, rather than a local variable in your function, you can use the <<- operator (double headed arrow) like this...
mat <- function(i) { for (k in i:10) { y[k] <<- k+1 f[k] <<- y[k-1] / 2 } } Type ?"<<-" for the help page. Michael On 10 November 2010 18:09, rnick <nikos.rachma...@gmail.com> wrote: > > Hi guys, > > Very new to R and your help would be highly appreciated for the following > problem. I am trying to create a simple function which registers values > within an array through a for loop. These are the steps I have followed: > > 1) Declared 2 global matrices > 2) Create function mat() with i as an input > 3) constructed the for loop > 4) called mat(2) > > The problem is that when i try to get y[4] and f[5] the output is: [1] NA > > my concern is that i am not addressing any of the following topics: > 1) definition of global variable > 2) the argument does not go through the for loop > 3) the matrices definition is not correct > 4) the function do not return any values > 4) other.. > > My code is listed below: > > y=c(NA) > f=c(NA) > mat<-function(i) > { > for (k in i:10) > { > y[k]=k+1 > f[k]=y[k-1]/2 > } > } > mat(2) > > Any thoughts or recommendations would be highly appreciated. > > Thanks in advance, > > N > -- > View this message in context: > http://r.789695.n4.nabble.com/Simple-Function-tp3035585p3035585.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@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@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.