R Cheatsheet: Anonymous functions

#An anonymous function is a function which is defined in the call of another function:

#For example we have a previously defined function called “evaluate”

evaluate

#This function has two arguments: the name of another function and a variable to make calculations with.

#The first time we write an “inline” new function which returns the last element of this vector

evaluate(function(x){x[length(x)]},c(8,4,0))
[1] 0

#Now we write an “inline” new function which returns the first element of this vector

> evaluate(function(x){x[1]},c(8,4,0))
[1] 8

 

Anuncios

R Cheatsheet: Logical Operators

#Equal to

==

#Non equal to

!=

#Less than

<

#Less than or equal to

<=

#Greater than

<

#Greater than or equal to

<=

#Negation (NOT operator), or to negate a boolean expression:

!(b==c)

#AND (Conjunction)

#we can use both ‘&’ and ‘&&’ the difference between this two symbols is that the first evaluates ALL the elements of a vector, and the second only the first element of a vector.

and_operator

Leer Más…

R Cheatsheet: Dates and Times

#R stores a date as the number of days counted from “Zero Day” which is January the first 1970. The same principle used by SAS, but the latter uses another “Start Date” or “Zero Day”

#Dates are represented as a “Date Class”

#On the other hand, times (number of seconds from “Start Date”) are represented by any of the following classes:

#POSIXct (a single integer value representing the time)

#POSIXlt (a list of  values representing the time)

#Defining a Date:

bday<-as.date(“1990-01-25”)

#If we need to see the “value” of a particular date class we have to unclass it:

bday

#So, it means it have passed 7329 since January 25th, 1990, the date stored in bday. Unclass is equivalent to the datepart() function of SAS.

#To obtain the current datetime, equals to TODAY() in SAS

dt<-Sys.time

date_and_time

#Of course we can use the POSIXlt to de-construct and obtain a singular value of our date.

posixlt

#strptime is a useful function you can use to convert time in a POSIXlt or POSIXct format.

R Cheatsheet: Coding Standards

  1. Use text files.
  2. Indent your code.
  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:

functions_2

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
add2<- function(x,y=0){
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]
}

columnmeanresult_cm