[R] assign connections automatically

Tim Howard tghoward at gw.dec.state.ny.us
Tue Feb 1 14:09:47 CET 2005


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




More information about the R-help mailing list