Skip to content

Instantly share code, notes, and snippets.

rcat <- function(n, labels=c(0, 1), pcts=NULL, seed=12345) {
set.seed(seed)
catvar <- rep(labels[1], n)
if(length(pcts)==0) {
interval <- n/length(labels)
start <- 1
for(i in 2:length(labels)) {
end <- start+interval
catvar[start:end] <- labels[i]
start <- end+1
@rblissett
rblissett / CreateMCGraph.R
Created January 24, 2017 03:18
Function to create stacked bar graph of a set of variables with the same categorical scale (e.g., survey responses in a question set)
# Get ranking graph for multiple choice
getmcgraph <- function(t, levels, items, sortby) {
t <- lapply(t, function(x) factor(x, levels=levels))
end <- data.frame(matrix(NA, nrow=1, ncol=length(levels)))
names(end) <- levels
for(i in 1:length(t)) {
end <- rbind(end, round(100*prop.table(table(t[i])), digits=2))
}
end <- end[-1,]
end <- cbind(items, end)
@rblissett
rblissett / RTutorial.R
Last active January 24, 2017 03:15
Code to accompany RTutorial_160930.pdf
## RTutorial.R
## Richard Blissett (rsl.bliss@gmail.com)
## Code to accompany RTutorial_160930.pdf
###########################################################
# Set up environment
###########################################################
# Clear environment
rm(list=ls())
@rblissett
rblissett / StringWrap.R
Created November 20, 2016 20:56
Two functions for wrapping strings in R
# String wrapping for a set of strings
wrap_strings <- function(vector_of_strings,width){
sapply(vector_of_strings,FUN=function(x) {paste(wrap_sentence(x,width=width))})
}
# Wraps a single sentence
wrap_sentence <- function(string, width) {
words <- unlist(strsplit(string, " "))
fullsentence <- ""
checklen <- ""
@rblissett
rblissett / ConvertCCDtoStata_School.do
Created October 27, 2016 21:33
File for completing the conversion of NCES SAS school universe files to Stata. Should be preceded by ConvertCCDtoStata_School.R.
/* ConvertCCDtoStata_School.do
Richard Blissett (rsl.bliss@gmail.com)
Finally processes data produced from ConvertCCDtoStata_School.R
*/
* Environment settings
set more off
clear all
* Basic information
@rblissett
rblissett / ConvertCCDtoStata_School.R
Last active October 27, 2016 21:32
Code for converting CCD SAS files from NCES to Stata. Code should be followed by ConvertCCDtoStata_School.do, which does the final formatting for the data sets.
## ConvertCCDtoStata_School.R
## Richard Blissett (rsl.bliss@gmail.com)
# Environment settings
rm(list=ls())
library(haven)
# Basic information
setwd("~/Documents/CCD Data/School")