-
Notifications
You must be signed in to change notification settings - Fork 13
/
class_5.Rmd
89 lines (71 loc) · 2.18 KB
/
class_5.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
---
title: "in-class coding"
author: "Julia Gallucci"
date: "16/12/2023"
output: html_document
---
From last class
We can also iterate over two lists simultaneously and apply a function to each corresponding pair of elements.
```{r}
library(purrr)
x <- list(1, 1, 1)
y <- list(10, 20, 30)
map2(x, y, ~ .x + .y)
#Note, anonymous function is a function defined without a specific name. Instead, it is defined inline within the code where it is needed. In the function above, we used the ~ (tilde) symbol followed by the expression .x + .y . The .x + .y represents the input parameter of the function
#the anonymous function ( ~ .x + .y ) takes two arguments, .x and .y , which represent the corresponding elements from x and y in each iteration. The function adds .x and .y to calculate the sum.
```
Simulation
```{r}
#uniform distribution
set.seed(123)
runif(n = 5)
hist(runif(10000))
set.seed(123)
runif(n = 10, min = 1, max = 20)
#normal distribution
set.seed(123)
rnorm(n = 10, mean = 5, sd = 1)
hist(rnorm(10000))
#sample
set.seed(123)
sample(c("a","b","c"),
size = 100,
replace = TRUE,
prob = c(0.1, 0.2, 0.7))
#random sample
set.seed(123)
simulated_data <-
tibble(X = runif(10, min = 0, max = 20),
Y = 3*X + rnorm(10, mean = 0, sd = 1))
simulated_data
simulated_data %>%
ggplot(aes(x = X, y = Y)) +
geom_point()
```
1. Write a greeting function that says “good morning”, “good afternoon”, or “good evening”, depending on the time of day.
```{r}
library(lubridate)
greeting <- function(){
current <- now()
current_hour <- hour(current)
greeting_output <-
case_when(
current_hour > 4 && current_hour < 12 ~ "good morning",
current_hour < 16 ~ "good afternoon",
TRUE ~ "good evening"
)
return(greeting_output)
}
greeting()
```
2-Simulate a dataset using a normal distribution with mean 100 and standard deviation 15 as variable X, and a quadratic transformation of X as variable Y. Graph your data.
```{r}
simulated_data <-
tibble(X = rnorm(n = 1000, mean = 100, sd = 15),
Y = X ^ 2)
simulated_data
simulated_data %>%
ggplot(aes(x = X, y =Y)) +
geom_point()
```
*Learners worked on exercise slide deck and presented their findings