#Author: Luke Watson-Sharer # Title: Module 3 Assignment 2 # Date: 09/18/2020 # Course: Geog 246 vignette: %\VignetteIndexEntry{5.3} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8}
mycalc <- function(x, y, fun) { if(fun == "sum") { o <- sum(x, y) } else if(fun == "subtract") { o <- (x - y) } else if(fun == "multiply") { o <- (x * y) } else if(fun == "divide") { o <- (x / y) } else { o <- paste("Not a recognized function") } return(o) }
#creating initial variables x <- 0:100 y <- 1:10 z <- 20
set.seed(1) #set seeds for consistent values v1 <- sample(x, z, replace = TRUE) #random variable v1 set.seed(2) v2 <- sample(y, z, replace = TRUE) # random variable v2 set.seed(3) v3 <- runif(z, min=0, max=1) # random variable v3 set.seed(4) g = letters[v2] #index v2 v4 = sample(g, 20, replace = TRUE) #random character v4 print(v1) # print our new values print(v2) print(v3) print(v4)
library(lws246) library(geospaar) # loading libraries
#create matrix values m1 <- cbind(v1, v2) m2 <- cbind(v2, v3) m3 <- cbind(v3, v4) # creating data frame and testing the outputs # do not name the dataframe df because it's a data type and c is a function so if you name it either of them it will confuse Rstudio and create errors. So is c was a vector it would be read as a function but because as a column name its a character string its not gonna mess with Rstudio d <- data.frame (v1, v2, v3, v4) print(d) # Test and print matrices and data frame print(m1) print(m2) print(m3) #Changing factor to character 1. as.character() function and 2. Convert a list to characters
colnames(d) <- c("a", "b", "c", "grp" ) #changing column names in data frame print(d) #Test new column names
s1 <- mycalc(v1, v2, "sum") s2 <- mycalc(v2, v3, "sum") s3 <- mycalc(v1, v3, "sum") s4 <- mycalc(m1, m1, "sum") s5 <- mycalc(m1, m2, "sum") d1 <- mycalc(v1, v2, "divide") d2 <- mycalc(v1, v3, "divide") d3 <- mycalc(v2, v3, "divide") d4 <- mycalc(m1, m1, "divide") d5 <- mycalc(m1, m2, "divide") s6 <- mycalc(m2, m3, "sum") d6 <- mycalc(m2, m3, "divide") print (s1) # print and test all calculations print (s2) print (s3) print (s4) print (s5) print (s6) #error print (d1) print (d2) print (d3) print (d4) print (d5) print (d6) #error
d(v1(1)) # add an (r, error= true) d1 <- mycalc(d[1,1],d[1,2],"multiply") #multiplying columns and rows d1 d2 <- mycalc(d[1:10, 1:3], d[1:10,1:3],"multiply") d2 d3 <- mycalc(d[d$grp == "e", c("a", "b")], d[d$grp == "e", c("c")], "divide") #dividing columns by name d3
t <- list(v1, m1, m2) t1 <- lapply(1:length(t), function(x) mycalc(t[[x]], v2, "multiply")) t2 <- sapply(1:length(t), function(x) mycalc(t[[x]], v2, "multiply")) # making all of the functions/the list and running sapply and lapply functions to for mycalc.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.