[R] Function not working

Duncan Murdoch murdoch.duncan at gmail.com
Mon Nov 1 19:26:20 CET 2010


On 01/11/2010 12:56 PM, Thomas Parr wrote:
> Below is the (really basic) script I am creating to call a function that
> sets the working directory, determines the number of files it will need to
> process in that directory, and creates a mask.  A "for" loop will eventually
> be added that will loop through the files (arrays) in that directory
> performing a baseline/zero correction and apply the mask - that will
> probably be a later plea for help. It is being designed for a specific
> idiot-proof purpose (obviously it found an idiot) which is why you just have
> to input the directory.
>
> This function was working fine on my x64 2.12.0 build of R on my home
> computer, but when I brought to work and started fiddling with the script on
> my x32 2.12.0 it didn't work. It sources without a problem, and I can call
> it without getting an error message, but all it seems willing to do is set
> the working directory.  Entering "n", "mat" or "mask" after that to make
> sure it ran results in "Error: object 'mat' not found."  I have copied and
> pasted the text into a new script, tried it with "\\" and with "/". Rebooted
> R, sourced from the command line and from the menu...  None of the functions
> I am using are exclusive to x64 or a package (that I know of).  I need to
> know why it was working on one computer and not the other because, in final
> form, it will be transported and used on different systems by people with
> minimal understanding of R.
I think it wasn't working on your x64 computer, but you happened to have 
existing variables named n, mat and mask, and you mistakenly thought 
your function was setting them.


> The call would look something like: EEMCORR("C:\\Documents and
> Settings\\User\\Desktop\\folder\\subfolder") or wherever they put the data
> arrays.
>
> EEMCORR<- function(location){
>
> #set working directory, find number of files in directory
> setwd(location)
> n<- (length(list.files(getwd())))-1
>
> #mask
> mat<-matrix(0, 20,20)
> mat[upper.tri(mat)]<-"ZZ"
> mask<- rbind((cbind(matrix(0,20,20),mat)),matrix(0,100,40))
> }
>

This function has local variables n, mat and mask, but never changes the 
values of global ones.  Generally functions that have such global side 
effects are a bad idea, but if you are sure you want to do it, use n <<- 
..., mat <<- ..., etc.  The <<- "superassignment" operator makes the 
assignment in a parent or global environment.

Duncan Murdoch

> Thanks for your keen eyes
>
> Thomas
>
> 	[[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.



More information about the R-help mailing list