Skip to content

Instantly share code, notes, and snippets.

@jeromyanglim
jeromyanglim / covlm.r
Last active July 26, 2023 17:51
Function that allows you to run a linear model on a covariance matrix using lavaan
# see
# http://stackoverflow.com/questions/20203485/why-is-source-gist-function-in-r-devtools-package-not-working
covlm <- function(dv, ivs, n, cov) {
# Assumes lavaan package
# library(lavaan)
# dv: charcter vector of length 1 with name of outcome variable
# ivs: character vector of names of predictors
# n: numeric vector of length 1: sample size
# cov: covariance matrix where row and column names
@jeromyanglim
jeromyanglim / import_qualtrics_csv
Last active February 23, 2017 15:09
Function that assists with importing CSV data from Qualtrics into R; it also allows for choosing which categorical variables should be numeric and which labelled.
import_csv_qualtrics <- function(file) {
# import a csv file exported from Qualtrics
# Qualtrics places variable labels in the second row.
# This function removes that second row and returns the data frame.
# taken from:
# http://lowlywonk.blogspot.com.au/2011/05/r-code-to-remove-second-line-of.html
DF <- read.csv(file, skip=2, header=FALSE)
DF2 <- read.csv(file)
names(DF) <- names(DF2)
DF
javascript:location %3D %27http://scholar.google.com/scholar%3Fq%3D%27%2Bescape(document.forms%5B0%5D.elements%5B%27q%27%5D.value)%3B
@jeromyanglim
jeromyanglim / makefile
Created November 4, 2017 04:24
example of a makefile that runs an r job and sends an email when done.
EMAIL=youremail@gmail.com
SERVER=username@yourserver.com
mode=standard # e.g., quick, standard, publication
all:
make models mode=$(mode)
make ppc mode=$(mode)
make standard-figures mode=$(mode)
make yhat mode=$(mode)
# Function to write data.frame to xlsx spreadsheet
write_xlsx <- function(data, file, sheetname = "Sheet1", rowNames = TRUE, ...) {
require("openxlsx")
wb <- createWorkbook()
addWorksheet(wb, sheetname)
writeData(wb, sheetname, data, rowNames = rowNames, ...)
saveWorkbook(wb, file = file, overwrite = TRUE)
}
# Example
@jeromyanglim
jeromyanglim / longlat2countr.r
Created September 1, 2022 00:51
Script for converting latitude and longitude coordinates (e.g., from Qualtrics) into country codes using R
# Script for converting latitude and longitude coordinates (e.g., from Qualtrics) into country codes using R
# Assumes data set is called rcases
# country from coords
library(sp)
# install.packages("rworldmap")
library(rworldmap)
# The single argument to this function, points, is a data.frame in which:
# - column 1 contains the longitude in degrees