[R] assign connections automatically

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Feb 1 14:34:36 CET 2005


You are assigning in the frame of the function, not in the user workspace.
See ?assign and try pos=1 (if that is what you intended) but it might well 
be better to return a list of objects.

On Tue, 1 Feb 2005, Tim Howard wrote:

> Hi all,
>   I am trying to create a function that will open connections to all
> files of
> one type within the working directory.
>   I've got the function to open the connections, but I am having a
> bugger of a
> time trying to get these connections named as objects in the workspace.
> I am at the point where I can do it outside of the function, but not
> inside, using assign.  I'm sure I'm missing something obvious about the
> inherent properties of functions.....
>
> #first six lines just setup for this example
>> x<-1:20
>> y<-20:40
>> z<-40:60
>> write(x, file="testx.txt")
>> write(y, file="testy.txt")
>> write(z, file="testz.txt")
>
>> inConnect <- function(){
> + fn <- dir(pattern="*.txt") # grab only *.txt files
> + fn2 <- gsub('.txt', "", fn) # removes the '.txt' from each string
> + for(i in 1:length(fn))
> + assign((fn2[[i]]),file(fn[i], open="r"))
> + }
>
>> showConnections()  #currently, no connections
>     description class mode text isopen can read can write
>> inConnect()  # run function
>> showConnections()  #the connections are now there
>  description class  mode text   isopen   can read can write
> 3 "testx.txt" "file" "r"  "text" "opened" "yes"    "no"
> 4 "testy.txt" "file" "r"  "text" "opened" "yes"    "no"
> 5 "testz.txt" "file" "r"  "text" "opened" "yes"    "no"
>> ls()  #but NOT there as objects
> [1] "fn"           "fn2"          "inConnect"    "last.warning"
> [5]   "x"            "y"            "z"
>
>> fn <- dir(pattern="*.txt")  #but if I do it manually
>> fn2 <- gsub('.txt', "", fn)
>> assign((fn2[[3]]),file(fn[3], open="r"))
>> ls()  #the connection, testz, appears
> [1] "fn"           "fn2"           "inConnect"    "last.warning"
> [5]  "testz"        "x"            "y"         "z"
>
> What am I missing? or is there a better way?
>
> I am using R 2.0.1 on a Windows2K box.
>
> Thanks so much!
> Tim Howard
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list