Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created September 10, 2012 02:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsparks/3688542 to your computer and use it in GitHub Desktop.
Save dsparks/3688542 to your computer and use it in GitHub Desktop.
Illustrating the use of str()
# Let's say you want to display a table of model coefficients
# in order of their significance,
# and you want to plot the distribution of model residuals,
# but you don't know how to access these values.
# Use str().
# Generate some random data
NN <- 1000
theData <- data.frame(Alpha = rnorm(NN),
Beta = rnorm(NN))
theData$Gamma <- theData$Alpha * 2 + theData$Beta / 2 + rnorm(NN)
# Model the random data
simpleModel <- lm(Gamma ~ Alpha + Beta, data = theData)
# Save the model summary
modelSummary <- summary(simpleModel)
is.list(modelSummary) # The model summary is a list
# which includes, among other things, a table of coefficients
# standard errors, etc.
# str() lets you investigate the structure of any R object:
str(modelSummary)
# Here we see an item called "coefficients," which we can access with the "$."
modelSummary$coefficients
# And here is our ordered table
modelSummary$coefficients[order(modelSummary$coefficients[, 3]), ]
# Likewise for the residuals. str() reveals an item called "residuals,"
# and we can easily plot their distribution.
plot(density(modelSummary$residuals))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment