Vectors and Dataframes

FOR 128: Lab 3

Published

September 12, 2024

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.

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)
  1. plt
  2. class(plt)
  3. names(plt)
  4. nrow(plt)
  5. ncol(plt)
  6. dim(plt)
  7. length(plt)
  8. plt[2:4,c(1,4)]
  9. plt[1:3,c("spp", "dbh")]
  10. plt$qual
  11. class(plt$qual)
  12. head(plt)
  13. tail(plt)
  14. head(plt, n=3)
  15. tail(plt, n=2)
  16. plt.cpy <- plt
  17. plt.cpy[1:3,1] <- c("pinust", "pinust", "acerru")
  18. plt.cpy[1:2,1] <- c("pinust", "pinust", "acerru")
  19. plt.cpy$live[8] <- FALSE
  20. plt.cpy[8,"live"] <- TRUE
  21. rep("ugs", nrow(plt.cpy))
  22. plt.cpy[,"status"] <- rep("ugs", nrow(plt.cpy))
  23. !TRUE
  24. colnames(plt.cpy)[4] <- "dead"
  25. plt.cpy$dead <- !plt$live
  26. plt.cpy <- plt[-(1:5),]
  27. plt.cpy <- plt[-1:5,]
  28. plt.cpy <- rbind(plt, c("some new spp", 100, "ugs", FALSE))
  29. plt.cpy <- cbind(plt, 1:nrow(plt))
  30. colnames(plt.cpy)[ncol(plt.cpy)] <- "tree.indx"
  31. 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")
  1. dim(fef)
  2. head(fef)
  3. tail(fef)
  4. sum(fef$height_ft)
  5. max(fef$height_ft)
  6. min(fef$height_ft)
  7. which.max(fef$height_ft)
  8. fef[which.max(fef$height_ft), ]
  9. fef[which.min(fef$height_ft), ]
  10. 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.