tags:

views:

132

answers:

3

Hi everybody,

I tried to pass a filepath to a function in R, but I failed =/ I hope someone here can help me.

>heat <- function(filepath) 
{ chicks <- read.table(file=filepath, dec=",", header=TRUE, sep="\t")
...
}

When I call the function, nothing happens...

>heat("/home/.../file.txt")

... and "chicks" is not found

>chicks
Error: Object 'chicks' not found

What is the correct way to pass a path to a function?

Best wishes from Germany, Phil

+2  A: 

You should be able to pass file paths as you have (if the file exists). You can also query file paths in R using list.files() [use the argument full.names=TRUE]. However, in this case I believe you cannot see chicks because it is local to the function so you will not be able to see this variable outside of the function. Furthermore, if your last expression is an assignment, I believe the output is not printed. Try

> heat <- function(filepath) { 
+   read.table(file=filepath, dec=",", header=TRUE, sep="\t")
+ }
> heat("/home/.../file.txt")

or

> chicks <- heat("/home/.../file.txt")
> chicks

and you should see chicks. Or if you want to see it printed while assigning, add parentheses around the statement:

> (chicks <- heat("/home/.../file.txt"))

If you want to assign to chicks within the function but still see it after the function has completed,

> heat <- function(filepath) { 
+   chicks <- read.table(file=filepath, dec=",", header=TRUE, sep="\t")
+   assign("chicks",chicks,globalenv())
+ }
Stephen
"However, in this case I believe you cannot see chicks because it is local to the function so you will not be able to see this variable outside of the function."Aaargh, that was the problem ^^Thanks a lot!! I should have asked earlier. Costed me about 2 hours :D
Philipp
+1  A: 

Also when working with paths, it is often helpful to test whether the file/folder exists:

heat <- function(filepath){
    if(!file.exists(filepath)){
        stop(sprintf("Filepath %s does not exist",filepath))
    }
    ...
}

In the example above, however, read.table will give an error message if the file does not exist.

nullglob
thanks, very usefull too :)
Philipp
A: 

The function can't know what you're trying to make the output. If you don't specify it, the output will be the last viable line, which may not always be what you want. Use return() to specify what should come out as an object.

heat <- function(filepath) {
 chicks <- read.table(file=filepath, dec=",", header=TRUE, sep="\t")
 ...
 return(chicks)
}

inpt <- heat("/.../file.txt")

Does this help with your problem?

Roman Luštrik
actually I don't need a return value, the function creates a heatmap of the input data, which is saved as a pdf file.The problem was, that I just wanted to return chicks to test, if the path was passed correctly. But this was not necessary at all. I just had to complete the code and all worked fine :-)Thanks anyway, I have still many things to learn :-)
Philipp