public
Created

Illustrating the use of str()

  • Download Gist
str example.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# 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))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.