This page is work in progress

This is a compilation of basic R utilities with outputs also for clarity.

RBasic1, RBasic2, RBasic3, data.table, dplyr, tidyr, RGIS, Leaflet

a <- c(2,3);b <- c(4,1)
df <- data.frame(a = c(2,3),b = c(4,1))
MyFn1 <- function(x,y){ return (cbind(x*y,x+y,x-y))}
MyFn1(df$a,df$b)
##      [,1] [,2] [,3]
## [1,]    8    6   -2
## [2,]    3    4    2
MyFn2 <- function(x,y){ return (c(x*y,x+y,x-y))}
MyFn2(df$a,df$b)
## [1]  8  3  6  4 -2  2
mapply(MyFn2,df$a,df$b)
##      [,1] [,2]
## [1,]    8    3
## [2,]    6    4
## [3,]   -2    2
#An example showind how to use sapply and match
match(c(1,2,1,1,3),c(2,1))
## [1]  2  1  2  2 NA
check1 <- data.frame(matrix(runif(15),nrow = 5))
check2 <- sapply(check1,function(x) x<0.3)
check2
##         X1    X2    X3
## [1,] FALSE FALSE FALSE
## [2,] FALSE FALSE FALSE
## [3,] FALSE FALSE  TRUE
## [4,] FALSE  TRUE FALSE
## [5,] FALSE FALSE  TRUE
apply(check2,1,function(x) match(TRUE,x))
## [1] NA NA  3  2  3
#lapply examples
lapply(1:3,function(n) n^2)                     
## [[1]]
## [1] 1
## 
## [[2]]
## [1] 4
## 
## [[3]]
## [1] 9
#lapply(1:nObs,function(n) gammaAll[n,][sortOrder[n,]])
#lapply(TAZSummary,function(n) table(is.na(n))) #get the distribution of na for each variable
# rep function examples
rep(1:4, 2)
rep(1:4, each = 2)       # not the same.
rep(1:4, c(2,2,2,2))     # same as second.
rep(1:4, c(2,1,2,1))
rep(1:4, each = 2, len = 4)    # first 4 only.
rep(1:4, each = 2, len = 10)   # 8 integers plus two recycled 1's.
rep(1:4, each = 2, times = 3)  # length 24, 3 complete replications
## [1] 1 2 3 4 1 2 3 4
## [1] 1 1 2 2 3 3 4 4
## [1] 1 1 2 2 3 3 4 4
## [1] 1 1 2 3 3 4
## [1] 1 1 2 2
##  [1] 1 1 2 2 3 3 4 4 1 1
##  [1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4
# missing variables
is.na(NA)
is.na(Inf)
## [1] TRUE
## [1] FALSE
is.finite(NA)
is.finite(Inf)
## [1] FALSE
## [1] FALSE
is.nan(NA)
is.nan(Inf)
is.nan(0/0)
is.nan(sqrt(-1))
## [1] FALSE
## [1] FALSE
## [1] TRUE
## [1] TRUE

***Date time formats

strptime("20/2/2006 11:16:16.683", "%d/%m/%Y %H:%M:%OS")
strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
strptime("1/22/2013 11:00:00 pm",format="%m/%d/%Y %I:%M:%S %p")
## [1] "2006-02-20 11:16:16 PST"
## [1] "2006-02-20 11:16:16 PST"
## [1] "2013-01-22 23:00:00 PST"