# R Cheatsheet: Coding Standards

1. Use text files.
3. Limit the width of your code( 80 columns is a good measure)

# R Cheatsheet: Functions (2)

#Know the arguments of a function (sd)

args(sd)

#In R a function also can return another function, for example: # R Cheatsheet: Utilities

#Get the Working directory:

getwd()

#Set the WK

setwd(“/folder1/folder2”)

#List files of a directory

list.files()

#Clear workspace

rm(list=ls())

# R Cheatsheet: Functions (1)

#A Simple Function. Including a Default value for second Argument
x+y
}

#Another example of a function. This one calculates those elements of a
#vector greater than a value
above<- function(x, n=10){
use<-x>n
x[use]
}  # R Cheatsheet: Missing Values

A numeric vector with NA values. NA describes a “missing” value:

x<-c(44, NA, 5, NA)

A vector containing 1000 draws from normal distribution:

y<-rnorm(1000)

A vector of 1000 NA

z<- rep(NA, 1000)

Sampling 100 elements and then store those values in a variable:

my_data<-sample(c(y,z),100)

A logical vector containing the result of asking weather a value is NA or not:

my_na<-is.na(my_data) sum(my_na) returns a total of NA because R interprets a NA as 1.

# R Cheatsheet: Subsetting Vectors

Displaying first n elements of a Vector:

x[1:10]

A logical vector checking whether an element is NA

is.na(x)

Subsetting to obtain a vector of all NAs:

x[is.na(x)]

A subset of non NAs elements

y<-x[!is.na(x)]

A subset of elements which meet a certain condition:

x[x>0]

# R Cheatsheet: Vectors

A Vector is a collection of n elements of the same class.

A numeric vector:

num_vect<-c(0.5, 55, -10,6)

If we need to know which elements of the previous vector are lesser than 1:

tf<-num_vect<1

And we obtain a Logical Vector A character vector:

my_char<-c(“my”, “name”, “is”)

Concatenate the individual elements of a vector with a ” ” (blank)

paste(my_char, collapse = ” “) Creating a new character vector with another element

my_name<-c(my_char, “Martin”)

paste(my_name, collapse = ” “)

Using paste() function in order to concatenate each individual element of two vectors: paste(LETTERS, 1:4, sep = “-“)

# R Cheatsheet: Working with Sequences

Basic Sequence:

1:10

Sequences using the seq() function specifying the incremental value

seq(1, 10, by=0.5)

Creating a sequence of n numbers:

my_seq<-seq(5, 10, length=30)

Three ways of creating a sequence of n elements:

1:length(my_seq)

seq(along.with =my_seq)

seq_along(my_seq)

Creating a sequence of (replicate) n elements:

rep(0, times=40)

Replicate a vector n times:

rep(c(0,1,2), times=10) # Swirl part three: Course Structure  