spp <- c("tsugca", "tsugca", "betual", "acerru", "pinust", "pinust", "betual", "acerru")
dbh <- c(15, 12, 6.6, 9.3, 28.1, 9.23, 15.3, 11.1)
qual <- c("ugs", "ags", "ags", "ugs", "ags", "ags", "ugs", "ags")
live <- c(TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE)
plt <- data.frame(spp, dbh, qual, live)Vectors and Dataframes
FOR 128: Lab 3
Getting started
Learning objectives
- Create, subset, and manipulate vectors and data frames.
- Practice reading data from external files.
- Get some practice writing R scripts.
Preperation
Create a new directory called lab_03 within your labs directory (e.g., ~/FOR_128/labs/lab_03). In RStudio set lab_03 as your working directory. Download and move the FEF_trees.csv file from the D2L lab page to your lab_03 directory.
Create a new script and save it as lab_03.R (it should save to your working directory).
Now, use our book, help “man” pages, Google, your intuition, and experimentation to describe the behavior of the code in each of the following questions. For each question, write and execute the code in each question then, using a comment #, add notes above the code to describe/define its behavior (see example script lab_03_example.R in the lab’s D2L page).
Questions
Functions and index subsetting of vectors and data frames
Use the code below to create the plt data frame.
pltclass(plt)names(plt)nrow(plt)ncol(plt)dim(plt)length(plt)plt[2:4,c(1,4)]plt[1:3,c("spp", "dbh")]plt$qualclass(plt$qual)head(plt)tail(plt)head(plt, n=3)tail(plt, n=2)plt.cpy <- pltplt.cpy[1:3,1] <- c("pinust", "pinust", "acerru")plt.cpy[1:2,1] <- c("pinust", "pinust", "acerru")plt.cpy$live[8] <- FALSEplt.cpy[8,"live"] <- TRUErep("ugs", nrow(plt.cpy))plt.cpy[,"status"] <- rep("ugs", nrow(plt.cpy))!TRUEcolnames(plt.cpy)[4] <- "dead"plt.cpy$dead <- !plt$liveplt.cpy <- plt[-(1:5),]plt.cpy <- plt[-1:5,]plt.cpy <- rbind(plt, c("some new spp", 100, "ugs", FALSE))plt.cpy <- cbind(plt, 1:nrow(plt))colnames(plt.cpy)[ncol(plt.cpy)] <- "tree.indx"str(plt)
Read the external data file FEF_trees.csv into R using the read.csv() function and call the resulting data frame fef.
fef <- read.csv("FEF_trees.csv")dim(fef)head(fef)tail(fef)sum(fef$height_ft)max(fef$height_ft)min(fef$height_ft)which.max(fef$height_ft)fef[which.max(fef$height_ft), ]fef[which.min(fef$height_ft), ]- In the previous two labs you did your work in a Quarto document. What are some ways the script you created for this lab are different from the Quarto document?
Wrap up
Congratulations! You’ve made it to the end of Lab 3. Submit your lab_03.R script to D2L.