Skip to content

General Code

Kirk Vanacore edited this page Jan 16, 2022 · 8 revisions

Checking & Setting Working Directory

 # Set working directory (all slashes must be forward / not back \)
setwd("File Path")

# Get the current working directory
getwd()

Installing & Loading Packages

This script looks to see if you have installed the packaged in the list, Installs them if you don't and then loads all the packages. 


####Installing & Loading Packages###
#create list of packages
packages = c("RPostgreSQL","RPostgres","psych", "lme4", "nlme", "ggplot2", "RColorBrewer", "tidyverse", "plyr", "ggExtra", "hexbin")
#load install
package.check <- lapply(packages, FUN = function(x) {
if (!require(x, character.only = TRUE)) {
install.packages(x, dependencies = TRUE)
library(x, character.only = TRUE)
}
}) 

#clear objects rm(packages, package.check)

No Scientific Notation

Stops outputs from using scientific notation

options(scipen=999)

Saving R Sessions

#save particular objects to an .Rdata file that can be loaded quickly/easily next time
save(x, y, df, file="mydata.RData")

#Load the above file
load ("mydata.RData")

#Save your entire session
save.image()
Clear Working Environment (w/exceptions)

Scripts to clear your variables/data frames from your environment 

rm(df)

#clear all 
rm(list=ls())

#clear all with exceptions
rm(list=setdiff(ls(), "X")) # X will remain

Read In/Out Data

#read in from a basic CSV file with row of headers
df <- read.csv(file="FILE NAME.csv", header=TRUE)

#read out a dataframe to a CSV
write.csv(df, "FILE NAME.csv")

#read in from an SPSS data file
> #requires the read.spss function from the "foreign" package; 
> #more options listed here: https://www.rdocumentation.org/packages/foreign/versions/0.8-75/topics/read.spss

data <- read.spss("Revere PowerUp ESSA Strong Data File.sav", 
                  use.value.labels = TRUE, 
                  to.data.frame = TRUE,
                 `use.missings = TRUE)

#Other options: header (default=TRUE), stringsAsFactors (default=TRUE), row.names (default=TRUE)

Clone this wiki locally