Skip to content

Instantly share code, notes, and snippets.

@jebyrnes
Last active August 29, 2015 13:56
Show Gist options
  • Save jebyrnes/8849410 to your computer and use it in GitHub Desktop.
Save jebyrnes/8849410 to your computer and use it in GitHub Desktop.
A demonstration of how to add rows with zeroes using melt and dcast. There are other ways, but this is pretty simple.
################################
# Problem: You have a ragged
# data frame where species that have not
# been seen as a site simply don't have a
# line in your data frame. You have a long
# data frame, but you want a long data frame
# where missing species have proper zeroes
#
# Solution: a combination of dcast and melt
# from the reshape2 package
#
# from: Jarrett Byrnes
# last updated Feb 6,2014
################################
#a starting data frame where not all species were found at all sites
startDF <- data.frame(species = c("Auk", "Auk", "Egret"), site=c(1,2,2), density=c(5,3,6))
startDF
#uh oh! There's no entry for Egret at site 1!
#We want an entry, and want it to have a density of 0
#cast the frame
library(reshape2)
#use dcast to make a wide frame with zeros
#dcast basically works as identifiers ~ new columns
#where new columns are the names of whatever it is you're interested in.
# Note, you can add things together, so, if we'd had something other than site
# say, transect, we could say site + transect ~ species
# value.var tells dcast what column we'll be working on for our fun.aggregate
wideZeroDF <- dcast(startDF, site~species,
fun.aggregate = sum,
value.var="density", fill.var=0)
wideZeroDF
#now we want to go long again, so, melt it is!
#we need to give the new column, whose names are the non-id var colmn
#names a name itself, as well as what we want to call the value
#otherwise, it will all defailt to variable and value
longZeroDF <- melt(wideZeroDF, id.vars="site", variable.name="species", value.name="density")
longZeroDF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment