flowchart LR A[Input] --> B{Function} --> C[Output]
R
Open R Sessions 2023
R
and RStudioR
for
loops, and big datatidyverse
[16th November]R
flowchart LR A[Input] --> B{Function} --> C[Output]
\[A = \pi r^2\]
\[A = \pi r^2\]
flowchart LR A[radius] --> B{"circle_area()"} --> C[area]
df <- data.frame(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
df$a <- (df$a - min(df$a, na.rm = TRUE)) /
(max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$b <- (df$b - min(df$b, na.rm = TRUE)) /
(max(df$b, na.rm = TRUE) - min(df$b, na.rm = TRUE))
df$c <- (df$c - min(df$c, na.rm = TRUE)) /
(max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
df$d <- (df$d - min(df$d, na.rm = TRUE)) /
(max(df$d, na.rm = TRUE) - min(df$d, na.rm = TRUE))
df <- data.frame(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
rescale_01 <- function(x) {
rng <- range(x, na.rm = TRUE)
rescaled <- (x - rng[1]) / (rng[2] - rng[1])
return(rescaled)
}
df$a <- rescale_01(df$a)
df$b <- rescale_01(df$b)
df$c <- rescale_01(df$c)
df$d <- rescale_01(df$d)
Three big advantages over using copy-and-paste:
[1] -0.2591254 0.1288432
R
enviroment, and “copy” them into the function[1] -0.2159416 0.1640188
[1] 110
R
will look in the environment where the function was definedreturn()
will not be evaluatedYou should consider writing a function if:
function(sample) {
# get standard error
# get alpha value
# get mean
# use qnorm to get quantiles of normal dist
# get ci with mean(sample) + se * qnorm(alpha)
# return ci
}
R
codeflowchart LR A[Function A] --> B{Main Script} C[Function B] --> B D[Function C] --> B E(Data) --> B B --> F(Output)
.R
files, and then call them into the “main” script, that defines your analysis.R
file, use source()
R
, and other methods might be more suitable for you (e.g. coding “notebooks” like Quarto/Jupyter)git
very clean and usefulYou can also work on previous exercises, or your own work. We are here to help with anything R
related!
Exercise session will be in Heden.
Thanks!