R - Architecture
Updated at 2017-10-14 10:29
R always points to a specific directory in your system. This directory is called a working directory and is used to load requested files.
# Prints current working directory.
getwd()
# [1] "/Users/ruksi/Projects/rworkspace"
# Change current working directory.
setwd("/Users/ruksi/Projects")
setwd("..")
You can seed the pseudo-random number generator to get consistent results.
set.seed(100)
poissonDistribution <- rpois(15, 8)
print(poissonDistribution)
# [1] 6 6 8 4 8 8 10 7 8 5 9 11 6 7 10
Writing files.
# Write stdout to a file until you call sink() another time.
sink("my_dump.txt")
x <- "Hello World!"
print(x)
write('What is this', stdout())
sink()
# Write object to file.
x <- "Hello World!"
write(x, "my_file_name")
# Write data frame to a file.
write.table(cars, "my_cars")
Reading files.
# Lists files in current directory.
list.files()
# [1] "test.R"
# Lists active R objects, even those loaded from other R files with "source".
x <- "Hello"
y <- "World"
ls()
# [1] "x" "y"
# Read data frame from a file.
my_cars <- read.table("my_cars")
Downloading files.
url <- "http://rfunction.com/code/1202/120222.R"
destination_file <- "120222.R"
download.file(url, destination_file)
Loading R code inside R code.
# Runs R code in current context.
source("my_function.R")
Using R packages.
# Shows where R will install packages.
print(.libPaths())
# Download and install package from remote repositories or local files.
install.packages("ggplot2")
# Loads package namespace and attached it to current context.
# Stops execution if can't load the package.
library("ggplot2")
# Same as library() but only returns FALSE if can't load the package.
require("ggplot2")
Remote repositories are called CRANs, Comprehensive R Archive Networks. They act as mirrors for R packages.
# The full list can be found at https://cran.r-project.org/
"http://cran.us.r-project.org"
"http://cran.uk.r-project.org"
You should define .Rprofile
in your project root.
# .Rprofile
# Set where to download R packages.
r <- getOption("repos")
r["CRAN"] <- "http://cran.uk.r-project.org"
options(repos = r)
rm(r)
# Where to install and search for packages.
# This also creates the direcotry if it doesn't exist,
# as if the assigned directory doesn't exist, it won't be used.
lib.path <- "./packages"
if (!dir.exists(lib.path)) {
dir.create(lib.path, recursive = TRUE)
}
.libPaths(lib.path)
rm(lib.path)
You should create a function to handle the installation and loading. This functions still has problems if the package doesn't exist, as the library() call will fail right after the install for some reason. But it will work if you run the program multiple times.
Load <- function(packageName) {
if (!require(packageName, character.only = TRUE)) {
install.packages(packageName)
library(packageName, character.only = TRUE)
}
}
Load("ggplot2")
ggplot(cars, aes(y = speed, x = dist)) +
geom_point()
Sources
- Google Developers R Programming Videos
- Try R