

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Putting Together Strings
paste('string1', 'string2', sep = '/')
paste(c('1', '2'), collapse = '/')
Split String
stringr::str_split(string = v1, pattern = '-')
Get Substring stringr::str_sub(string = v1, start = 1, end = 3)
Match String
isJohnFound <- stringr::str_ detect(string = df1$col1, pattern = ignore.case('John'))
df1[isJohnFound, c('col1', ...)]
help(functionName) or ?functionName
Help Home Page help.start() Special Character Help help('[') Search Help help.search(..)or ??.. Search Function - with Partial Name apropos('mea')
See Example(s) example(topic)
Display Object Name objects() or ls() Remove Object rm(object1, object2,..)
Notes:
Only trust reliable R packages i.e., 'ggplot2' for plotting, 'sp' for dealing spatial data, 'reshape2', 'survival', etc.
Load Package library(packageName)or require(packageName) Unload Package detach(packageName)
Note: require() returns the status(True/False)
Store any number of items of ANY type
Create List list1 <- list(first = 'a', ...)
Create Empty List vector(mode = 'list', length = 3) Get Element list1[[1]] or list1[['first']] Append Using Numeric Index list1[[6]] <- 2
Append Using Name list1[['newElement']] <- 2
Note: repeatedly appending to list, vector, data.frame etc. is expensive, it is best to create a list of a certain size, then fill it.
Create Data Frame df1 <- data.frame(col1 = v1, col2 = v2, v3) Dimension nrow(df1); ncol(df1); dim(df1) Get/Set Column Names
names(df1) names(df1) <- c(...) Get/Set Row Names
rownames(df1) rownames(df1) <- c(...) Preview head(df1, n = 10); tail(...) Get Data Type class(df1) # is data.frame
Index by Column(s)
df1['col1']or df1[1];† df1[c('col1', 'col3')] or df1[c(1, 3)] Index by Rows and Columns
df1[c(1, 3), 2:3] # returns data from row 1 & 3, columns 2 to 3
† Index method: df1$col1 or df1[, 'col1'] or df1[, 1] returns as a vector. To return single column
Check data type : class(variable)
nchar(variable) # length of a character or numeric
date2 <- as.POSIXct('2012-06-28 18:00')
Note: Use 'lubridate' and 'chron' packages to work with Dates
data.frame while using single-square brackets, use ‘drop’: df1[, 'col1', drop = FALSE]
What is a data.table
Create data.table from data.frame data.table(df1)
Index by Column(s)*^
dt1[, 'col1', with = FALSE] or dt1[, list(col1)] Show info for each data.table in memory (i.e., size, ...) tables()
Show Keys in data.table key(dt1) Create index for col1 and reorder data according to col setkey(dt1, col1)
Use Key to Select Data
dt1[c('col1Value1', 'col1Value2'), ] Multiple Key Select dt1[J('1', c('2', '3')), ]
Aggregation**
dt1[, list(col1 = mean(col1)), by = col2] dt1[, list(col1 = mean(col1), col2Sum = sum(col2)), by = list(col3, col4)]
** Aggregate and d*ply functions will work, but built-in aggregation functionality of data table is faster
Create Matrix matrix1 <- matrix(1:10, nrow = 5),^ #^ fills rows 1 to 5, column 1 with 1:5, and column 2 with 6: Matrix Multiplication
matrix1 %*% t(matrix2)
D ata MunGinG FunctionS anD controlS
D ata
D ata reShapinG
Created by A. Colton and S. Chen
Based on content from 'R for Everyone' by Jared Lander
Updated: December 2, 2015
Melt Data - from column to row
reshape2.melt(df1, id.vars = c('col1', 'col2'), variable. name = 'newCol1', value.name = 'newCol2') Cast Data - from row to column
reshape2.dcast(df1, col1 + col2 ~ newCol1, value.var = 'newCol2')
If df1 has 3 more columns, col3 to col5, 'melting' creates a new df that has 3 rows for each combination of col and col2, with the values coming from the respective col to col5.
data.frame from two vectors cbind(v1, v2)
data.frame combining df1 and df2 columns cbind(df1, df2)
3.1 Merge
3.2 Join
join(x = df1, y = df2, by = c('col1', 'col3'))
3.3 data.table
dt1 <- data.table(df1, key = c('1', '2')), dt2 <- ...‡
dt1[dt2]
‡ Data table join requires specifying the keys for the data tables
lapply
Applies a function to each element of a list and returns the results as a list
sapply
Same as lapply except return the results as a vector
Note: lapply & sapply can both take a vector as input, a vector is technically a form of list
In the example below diamonds is a data.frame; price, cut, color etc. are columns of diamonds.
aggregate(price ~ cut, diamonds, mean)
aggregate(price ~ cut + color, diamonds, mean) # group by cut and color aggregate(cbind(price, carat) ~ cut, diamonds, mean) # get the average price and average carat of different cuts
ddply
Takes a data.frame, splits it according to some variable(s), performs a desired action on it and returns a data.frame
llply
group_by(), sample_n()
each() - supply multiple functions to a function like aggregate aggregate(price ~ cut, diamonds, each(mean, median))
Connect to Database db1 <- RODBC::odbcConnect('conStr') Query Database
df1 <- RODBC::sqlQuery(db1, 'SELECT ..', stringAsFactors = FALSE) Close Connection RODBC::odbcClose(db1)
R and some packages come with data included. List Available Datasets data() List Available Datasets in a Specific Package
data(package = 'ggplot2')
NULL is not missing, it’s nothingness. NULL is atomical and cannot exist within a vector. If used inside a vector, it simply disappears. Check Missing Data is.na() Avoid Using is.null()
GraphicS
hist(df1$col1, main = 'title', xlab = 'x axis label') plot(col2 ~ col1, data = df1), aka y ~ x or plot(x, y)
Create Function say_hello <- function(first, last = 'hola') { } Call Function say_hello(first = 'hello')
do.call(mean, args = list(first = '1st'))
if { } else ifelse Works with Vectorized Argument No Yes Most Efficient for Non-Vectorized Argument Yes No Works with NA *^ No Yes Use &&, || **†^ Yes No Use &, | ***†^ No Yes
** &&, || is best used in if, since it only compares the first element of vector from each side *** (^) &, | is necessary for ifelse, as it compares every element of vector from each side
† &&, || are similar to if in that they don’t work with vectors, where ifelse, &, | work with vectors