Chapter 13 Advanced Coding Tips
13.1 Grammar and Syntax
13.1.1 Regex expressions and symbols
str_remove(html$`Market Price`, pattern = "$") # doesn't remove the $ sign
str_remove(html$`Market Price`, pattern = "\\$") # works
13.1.2 The colon-equals (:=
) operator
Sometimes when making a function you need to use the colon-equals operator, rather than just the normal <- or = assignment operators
Specifically, when you have multiple named arguments in your function…Read my question and someone’s answer on this blogpost: https://community.rstudio.com/t/help-creating-simple-function/109011/2
function(df, col, newCol_name){
# drop all NA's so the function can work properly
=df |> drop_na({{col}})
df_NAdropped
# apply the function, saving it in a small tibble with only the outlier column and a key to join by
=df_NAdropped |>
outliers_key::mutate(outliers=dplyr::if_else(round(abs({{col}}-median({{col}}))/(1.483*mad({{col}}, constant = 1)),2)>2.24,1,0)) |>
dplyrselect(subject_id, outliers)
# join back together
=df |> left_join(outliers_key, by=c("subject_id"))
df
=df |>
num.outliers::filter(outliers==1) |>
dplyr::count()
dplyr
$outliers=replace_na(df$outliers, 999)
df=df |> rename({{newCol_name}}:="outliers")
df
message(paste0(num.outliers, " outlier(s) detected"))
return(df)
}
13.2 Creating a package
https://rstudio4edu.github.io/rstudio4edu-book/data-pkg.html
13.2.3 Linking Git and Github
view this detailed guide by Jenny Bryan, and this YouTube video if you want the full guide; or just follow the TL;DR below.
Quick summary of steps in YouTube video:
Open project folder in Windows Explorer and click in the URL bar, then type
cmd
to open command promptIf there are any pre-existing git files or repository info there, remove it with the following:
rd .git /S/Q
Tell git to create a new repo by typing:
git init
Then tell it to include all files in the current place by typing:
git add .
Commit these files with:
git commit -m "Initial commit"
At this point you’ve created a git and GitHub repo each; now link them with:
git remote add origin [https URL of GitHub repo]
Push all these changes live with:
git push -u origin master
13.3 Creating a bookdown
https://www.youtube.com/watch?app=desktop&v=m5D-yoH416Y&feature=youtu.be