R Snippets - PHIntelligence/CodingStandards GitHub Wiki

Installing Packages

To install packages, use the method option "libcurl", which prevents 403 errors

install.packages("fingertipsR", method = "libcurl")

Environment

Remove all objects from the global environment, and run the garbage collector to free memory.

rm(list=ls())

gc()

Data Frames

Maximum length of each column:

ColumnLengths <- lapply(df, function(x) max(nchar(x, keepNA = FALSE)))

Data type for each column:

ColumnTypes   <- sapply(df, class)

CSV

Fast write a CSV to be used in a SQL BULK LOAD command

library(data.table)

fwrite(df, "data.txt", sep = "|", col.names = FALSE, row.names = FALSE, quote = FALSE, eol = "\n")

SQL to load it:

IF OBJECT_ID('dbo.data') IS NOT NULL DROP TABLE dbo.data
CREATE TABLE dbo.data(

)
GO
 BULK INSERT dbo.data
         FROM '\\ServerName\Folder\data.txt'
         WITH
         (
          FIRSTROW               = 1
         ,FIELDTERMINATOR    = '|'
         ,ROWTERMINATOR        = '0x0a'
         ,KEEPNULLS
         )
GO

ggplot2

Drag and drop interface for creating ggplot2 charts with the ability to export the code. Taken from this post:

#Install & load relevant packages
if (!require(dplyr)) install.packages("dplyr", method = "libcurl")
if (!require(shiny)) install.packages("shiny", method = "libcurl")
if (!require(ggplot2)) install.packages("ggplot2", method = "libcurl")
if (!require(esquisse)) install.packages("esquisse", method = "libcurl")
if (!require(fingertipsR)) install.packages("fingertipsR", method = "libcurl")

#Get fingertips data, load to environment and shiny app below picks it up
ft_data <- fingertips_data(10101) %>%
  filter(AreaType == "County & UA" & ParentName == "East Midlands region")

#Create ggplot with drag and drop
esquisser(ft_data)