Skip to content

Commit

Permalink
Upload R code for week 4.
Browse files Browse the repository at this point in the history
  • Loading branch information
Euphrasiologist committed Oct 18, 2024
1 parent ea8bb72 commit 0e744b1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
3 changes: 1 addition & 2 deletions weeks/week4/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ abline(h = mean(d), col = "red", lty = 2)

# show lines from each of our points to the mean
for (i in 1:length(d)) {
print(paste(c(i, i), c(d[i], mean(d))))
lines(c(i, i), c(d[i], mean(d)), col = "blue")
}

Expand All @@ -75,4 +74,4 @@ degrees_of_freedom <- length(d) - 1
mean_squared_residuals <- sum_of_squares / degrees_of_freedom
```

Now we will compute the variance by hand.
Now we will compute the variance by hand, using the code above!
32 changes: 32 additions & 0 deletions weeks/week4/week4.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
x <- c(1, 2, 3, 4, 5, 10, 1000)

# edit your median function so that it works
# for both even and odd length vectors
my.median <- function(x) {
# is the vector even length??
is_vector_even <- length(x) %% 2 == 0
# sort
sorted_vec <- sort(x)
# get the mid point
index_of_mid_point <- length(sorted_vec) / 2

if (is_vector_even) {
# ...
first_midpoint <- sorted_vec[index_of_mid_point]
second_midpoint <- sorted_vec[index_of_mid_point + 1]

return((first_midpoint + second_midpoint) / 2)
} else {
to_integer <- ceiling(index_of_mid_point)
first_midpoint <- sorted_vec[to_integer]
return(first_midpoint)
}
}

vec <- c(1, 2, 3, 4, 5, 10) # 3.5
vec2 <- c(1, 2, 3, 4, 5, 10, 1000) # 4

my.median(vec2)
median(vec2)

my.median(vec2) == median(vec2)

0 comments on commit 0e744b1

Please sign in to comment.