Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a filepath to a R function?

Tags:

function

path

r

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?

like image 946
Philipp Avatar asked Nov 25 '25 21:11

Philipp


1 Answers

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())
+ }
like image 161
hatmatrix Avatar answered Nov 28 '25 17:11

hatmatrix