This script displays key features of a basic R script in the form of an RMarkdown file which integrates text and R code in code chunks.
At the top of .RMD files is a YAML header (not shown in rendered documents).
YAML is a markup language for formatting documents (“Yet Another Markup Language” some call it).
In RStudio, .Rmd files can be run in “notebook mode” with some output produced BELOW the code chunk. This is the default, and I usually turn it off.
Code chunks start with 3 ticks and r in brackets.
Comments can be included in chunks.
Click on the right-pointing triangle to run it (among other ways).
This 1st line of code runs install.packages() to download the R library called “scatterplot3d” from a website. You usually only have to run install.packages() once a semester to download the library for either the first time or to get the most recent version.
Uncomment the line of code if you have never downloaded the package before.
#code chunk starts here
## download from website
# install.packages("scatterplot3d")
## load package into memory
library(scatterplot3d)
## Warning: package 'scatterplot3d' was built under R version 4.2.1
# code chunk ends here
Code chunks start with 3 ticks.
# code chunk starts
stem_density <- c(483, 521, 531, 451, 513, 547,
500, 561, 478, 634, 582, 531, 532, 554, 549)
basal_area <- c(32.6,41.5,44.2,37.6,42.1,34.0,
27.7,34.2,30.2,28.7,34.0,34.6,30.9,27.5,27.4)
tree_height_m <- c(47.6,42.6,43.2,47.9,48.0,33.6,
33.2,32.6,31.9,37.5,35.1,38.2,32.5,35.8,35.8)
altitude <- c(237,246,360,392,396,528,567,580,
605,627,650,668,721,850,909)
# code chunk ends
df <- data.frame(stem_density,
basal_area,
tree_height_m,
altitude)
If you are in notebook mode while in RStudio, the code below will show the output below the code chunk; otherwise it will show up in the RStudio console. It will always be printed out when the document is rendered.
head(df)
## stem_density basal_area tree_height_m altitude
## 1 483 32.6 47.6 237
## 2 521 41.5 42.6 246
## 3 531 44.2 43.2 360
## 4 451 37.6 47.9 392
## 5 513 42.1 48.0 396
## 6 547 34.0 33.6 528
Again, if you are in notebook mode, this plot will show the output below the code chunk; otherwise it will show up in the RStudio console.
scatterplot3d(x = df$stem_density,
y = df$basal_area,
z = df$tree_height_m,
cex.symbols = 1,
type = "h")
RMarkdown is a markup language, so RMarkdown files can be converted to several forms as long as you have the proper tools installed on your computer. This is called rendering. Types of output include
Consult the help file using ?scatterplot3d and change the viewing angle of the plot.