Source Code Files in R
[This article was first published on R-Chart, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
R’s interactive programming style is similar to what I have seen in other environments (e.g. ruby’s irb and Oracle’s SQL*Plus, etc). There are a few commands that you need to be aware of to get up and running with developing R programs.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
To identify your current working directory:
getwd()
This is relevant when you are reading or writing out data or programs. It becomes more important as you move from doing simple interactive sequences of commands to codifying your work in R functions, objects and packages. To change this directory, you can specify a different relative or absolute path:
setwd(../Desktop)
R functions are the simplest building blocks that you are likely to use in development. They provide a mechanism for encapsulating a reusable sequence of commands. A simple example of how to create a function within an R session:
hello=function(){cat(“Hello\n”)}
As you continue to work with a function, you will likely use an external editor. You can specify the editor that will be invoked.
options(editor=”notepad”)
The editor is then invoked whenever you want to modify code using the edit command.
hello=edit(hello)
Rather than starting with an interactive session, you can also start with a specific text file containing R source code. This approach more closely mirrors development in other programming languages. The file can be opened and executed as follows:
source(‘Hello.R’)
To run the function, simply call it with any relevant parameters – but make sure to include the parenthesis:
hello()
If you call a function without the parenthesis, a listing of the contents of the function will be displayed. This feature is useful when analyzing how functions provided in other R packages have been implemented.
To leave a comment for the author, please follow the link and comment on their blog: R-Chart.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.