[R] Execution of a function

R. Michael Weylandt michael.weylandt at gmail.com
Tue Aug 7 23:24:08 CEST 2012


Please do keep your replies on the R help list.

On Tue, Aug 7, 2012 at 4:17 PM, hafida goual <hafida-06 at hotmail.fr> wrote:
>
> HI
>>
>>I know my questions are debile, but please I'm debutante.
>
>>> source("functionaj")
> Error in file(filename, "r", encoding = encoding) :
>   cannot open the connection
> In addition: Warning message:
> In file(filename, "r", encoding = encoding) :
>   cannot open file 'functionaj': No such file or directory
>
>> source(functionaj)
> Error in source(functionaj) : object 'functionaj' not found
>
>> source('functionaj')
> Error in file(filename, "r", encoding = encoding) :
>   cannot open the connection
> In addition: Warning message:
> In file(filename, "r", encoding = encoding) :
>   cannot open file 'functionaj': No such file or directory
>

Unlike Matlab, R makes no connection between the name of a function
and the name of the file wherein it is defined.

Say I am at my shell prompt and I create a trivial file like so:

$ echo "test <- function(x) return(x)" > test.R

I can then start R and see if my function exists:

R> test(3) # Error because test() is not yet defined.

But then I can source my file

R> source("test.R")

R> test(3) # it works!
[1] 3

But the name doesn't have to make any sense: back at the shell prompt

echo "test2 <- function(x) return(x + 1)" > flub.R

now in R

R>  source("flub.R")

R> flub(3) # Does not exist

R> test2(3)  # Works as expected.
[1] 4

If you are on Windows, the command

source(file.choose())

might be of help.

Hope this helps clarify things,

Michael

>>THANKS AGAIN AGAIN
> hafida
>



More information about the R-help mailing list