The version object in R holds information about the current R version you are running.
Code
version
_
platform aarch64-apple-darwin20
arch aarch64
os darwin20
system aarch64, darwin20
status
major 4
minor 5.1
year 2025
month 06
day 13
svn rev 88306
language R
version.string R version 4.5.1 (2025-06-13)
nickname Great Square Root
2 Work with files
2.1 Get current directory
The getwd() function returns your current working directory as a string.
Code
getwd()
2.2 Get all file names under the current directory
The list.files() function returns a character vector of file and directory names in the specified directory. Without an argument, it lists files in the current directory.
Code
list.files()
[1] "1 basic R_files" "1 basic R.qmd"
[3] "1 basic R.rmarkdown" "1-basic-R.rmarkdown"
[5] "2 probability.qmd" "3 Statistics.qmd"
[7] "5 R boook.qmd" "6 data analytic in R book.qmd"
[9] "7 error handling.qmd" "hotels.csv"
[11] "images" "renv"
2.3 Get all file names under one level up directory
This code scrapes a table from a Wikipedia page. It uses rvest to read the HTML content, html_table to extract tables, janitor::clean_names to clean up column names, and dplyr verbs (filter, mutate) to clean the data.
# A tibble: 6 × 8
year western_champion coach result eastern_champion coach_2 finals_mvp_a
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 2020 Los Angeles Lakers (… Fran… 4–2 Miami Heat (5) … Erik S… LeBron James
2 2021 Phoenix Suns (2) (3,… Mont… 2–4 Milwaukee Bucks… Mike B… Giannis Ant…
3 2022 Golden State Warrior… Stev… 4–2 Boston Celtics … Ime Ud… Stephen Cur…
4 2023 Denver Nuggets (1) (… Mich… 4–1 Miami Heat (8) … Erik S… Nikola Jokić
5 2024 Dallas Mavericks (5)… Jaso… 1–4 Boston Celtics … Joe Ma… Jaylen Brown
6 2025 Oklahoma City Thunde… Mark… 4–3 Indiana Pacers … Rick C… Shai Gilgeo…
# ℹ 1 more variable:
# mw_parser_output_tooltip_dotted_border_bottom_1px_dotted_cursor_help_ref <chr>
3 Handle errors
tryCatch allows you to handle errors gracefully. The code in the first block is executed. If an error occurs, the error function is called.
Code
tryCatch({1+who # This will cause an error because 'who' is not defined},error=function(e){message(paste0('Here is some error:',e))})print('end of the code chunk')
[1] "end of the code chunk"
4 Condition with if/elif/else
This is a standard conditional statement. It checks a condition and executes different code blocks based on whether the condition is true or false.
Code
x <--5if(x >10){print("Non-negative number and better than 10")} elseif (x >0) {print("Non-negative number and better than 0")} else {print("Negative number")}
[1] "Negative number"
5 Loops
5.1 for Loop
A for loop iterates over a sequence of values.
Code
for (x in1:4) {print(x)}
[1] 1
[1] 2
[1] 3
[1] 4
break exits the loop prematurely.
Code
for (x in1:6) {if (x ==4) {break}print(x)}
[1] 1
[1] 2
[1] 3
next skips the current iteration and proceeds to the next one.
Code
for (x in1:6) {if (x ==4) {next}print(x)}
[1] 1
[1] 2
[1] 3
[1] 5
[1] 6
5.2 Using map() function for loops
The map functions from the purrr package (part of tidyverse) provide a more functional approach to iteration. map returns a list, map_dbl returns a numeric vector, and map_chr returns a character vector.
Code
library(tidyverse)
Code
map(1:3, \(x) x+2 )
[[1]]
[1] 3
[[2]]
[1] 4
[[3]]
[1] 5
Code
map_dbl(1:3, \(x) x+2 )
[1] 3 4 5
Code
map_chr(1:3, \(x) x+2 )
[1] "3.000000" "4.000000" "5.000000"
5.3 Error handling in a for loop: printing out errors
You can use tryCatch inside a loop to handle errors on a per-iteration basis.
A while loop continues as long as a condition is true.
Code
i <-1while (i <6) {print(i) i <- i +1}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
5.5 Error handling in a while loop: retrying until the error is gone
This example shows a while loop that attempts to run code that causes an error. The tryCatch block catches the error and modifies a variable, allowing the loop to eventually terminate.
Code
i=0a=0while (i <4) { a=a+1print(i)tryCatch({ asdfgaergae5gh5hae5h # This will cause an error i=i+1 },error =function(msg){print('eeeeeeee') i=i-1print(paste0("new i : ",i)) })if(a>10){break} # Safety break to prevent an infinite loop }
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
6 Functions
6.1 Without Arguments
This defines and calls a simple function that takes no arguments.
The args() function displays the arguments of a function.
Code
args(adding_ten)
function (x = 10)
NULL
6.5 Warning in function
The warning() function issues a warning message without stopping the execution of the function.
Code
adding_ten <-function(x=10) { a=x+10if(a>50){warning('its better than 50') }return(a)}adding_ten(100)
[1] 110
6.6 Stop in function
The stop() function halts the execution of the function and prints an error message.
Code
adding_ten <-function(x=10) { a=x+10if(a>50){stop('its better than 50') }return(a)}
6.7 Use try to bypass errors
The try() function is a simplified version of tryCatch. It runs an expression and if an error occurs, it returns an object of class try-error but allows the script to continue.
Code
try(adding_ten(100))
[1] 110
Code
5+10
[1] 15
7 Program running time
This code measures the time it takes to run a piece of code by recording the start and end times.
---title: "Basic R"author: "Tony Duan"execute: warning: false error: falseformat: html: toc: true toc-location: right code-fold: show code-tools: true number-sections: true code-block-bg: true code-block-border-left: "#31BAE9"---{width="300"}# R versionThe `version` object in R holds information about the current R version you are running.```{r}version```# Work with files## Get current directoryThe `getwd()` function returns your current working directory as a string.```{r}#| eval: falsegetwd()```## Get all file names under the current directoryThe `list.files()` function returns a character vector of file and directory names in the specified directory. Without an argument, it lists files in the current directory.```{r}list.files()```## Get all file names under one level up directoryYou can use `..` to refer to the parent directory.```{r}list.files('../')```## Get file infoThe `file.info()` function returns a data frame with information about the specified file, such as its size, creation time, and modification time.```{r}#| eval: falsefile.info("6 data analytic in R book.qmd")```## Create folderThe `dir.create()` function creates a new directory (folder).```{r}#| eval: falsedir.create('testing_folder')```## Delete folder/fileThe `file.remove()` function can be used to delete files. To delete an empty directory, you can also use `unlink()`.```{r}#| eval: falsefile.remove('testing_folder')```## Copy fileThe `file_copy()` function from the `fs` package copies files from one location to another.```{r}#| eval: falselibrary(fs)file_copy('test.csv', 'test2.csv')```## Download file from the internetThe `download.file()` function downloads a file from a given URL.```{r}#| eval: falseurl="https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-02-11/hotels.csv"download.file(url = url, destfile ="hotels.csv")```## Download table from the internetThis code scrapes a table from a Wikipedia page. It uses `rvest` to read the HTML content, `html_table` to extract tables, `janitor::clean_names` to clean up column names, and `dplyr` verbs (`filter`, `mutate`) to clean the data.```{r}library(tidyverse)library(rvest)library(janitor)nba_wiki_url='https://en.wikipedia.org/wiki/List_of_NBA_champions'nba_wiki_data001=nba_wiki_url %>%read_html() %>%html_table()nba_wiki_data002=nba_wiki_data001[[2]] %>%clean_names()nba_wiki_data003=nba_wiki_data002 %>%filter(!row_number() %in%c(1, 5)) %>%mutate(year=str_sub(year, 1, 4))tail(nba_wiki_data003)```# Handle errors`tryCatch` allows you to handle errors gracefully. The code in the first block is executed. If an error occurs, the `error` function is called.```{r}tryCatch({1+who # This will cause an error because 'who' is not defined},error=function(e){message(paste0('Here is some error:',e))})print('end of the code chunk')```# Condition with if/elif/elseThis is a standard conditional statement. It checks a condition and executes different code blocks based on whether the condition is true or false.```{r}x <--5if(x >10){print("Non-negative number and better than 10")} elseif (x >0) {print("Non-negative number and better than 0")} else {print("Negative number")}```# Loops## for LoopA `for` loop iterates over a sequence of values.```{r}for (x in1:4) {print(x)}````break` exits the loop prematurely.```{r}for (x in1:6) {if (x ==4) {break}print(x)}````next` skips the current iteration and proceeds to the next one.```{r}for (x in1:6) {if (x ==4) {next}print(x)}```## Using map() function for loopsThe `map` functions from the `purrr` package (part of `tidyverse`) provide a more functional approach to iteration. `map` returns a list, `map_dbl` returns a numeric vector, and `map_chr` returns a character vector.```{r}library(tidyverse)``````{r}map(1:3, \(x) x+2 )``````{r}map_dbl(1:3, \(x) x+2 )``````{r}map_chr(1:3, \(x) x+2 )```## Error handling in a for loop: printing out errorsYou can use `tryCatch` inside a loop to handle errors on a per-iteration basis.```{r}stuff <-list(12, 9, 2, "cat", 25, 10, "bird")loop_num=0for (i in1:6) { loop_num=loop_num+1tryCatch (print(1+i),error =function(e){message(paste("An error occurred for loop num", loop_num,":\n"), e) })}```## while LoopA `while` loop continues as long as a condition is true.```{r}i <-1while (i <6) {print(i) i <- i +1}```## Error handling in a while loop: retrying until the error is goneThis example shows a `while` loop that attempts to run code that causes an error. The `tryCatch` block catches the error and modifies a variable, allowing the loop to eventually terminate.```{r}i=0a=0while (i <4) { a=a+1print(i)tryCatch({ asdfgaergae5gh5hae5h # This will cause an error i=i+1 },error =function(msg){print('eeeeeeee') i=i-1print(paste0("new i : ",i)) })if(a>10){break} # Safety break to prevent an infinite loop }```# Functions## Without ArgumentsThis defines and calls a simple function that takes no arguments.```{r}my_function <-function() { print("Hello World!")}my_function()```## With ArgumentsThis function takes one argument, `x`, and returns its value plus 10.```{r}adding_ten <-function(x) { a=x+10return(a)}adding_ten(5)```## With default ArgumentsThis function has a default value for `x`. If the function is called without an argument for `x`, the default value of 10 is used.```{r}adding_ten <-function(x=10) { a=x+10return(a)}adding_ten()```## Check function ArgumentsThe `args()` function displays the arguments of a function.```{r}args(adding_ten)```## Warning in functionThe `warning()` function issues a warning message without stopping the execution of the function.```{r}adding_ten <-function(x=10) { a=x+10if(a>50){warning('its better than 50') }return(a)}adding_ten(100)```## Stop in functionThe `stop()` function halts the execution of the function and prints an error message.```{r}#| eval: falseadding_ten <-function(x=10) { a=x+10if(a>50){stop('its better than 50') }return(a)}```## Use try to bypass errorsThe `try()` function is a simplified version of `tryCatch`. It runs an expression and if an error occurs, it returns an object of class `try-error` but allows the script to continue.```{r}try(adding_ten(100))5+10```# Program running timeThis code measures the time it takes to run a piece of code by recording the start and end times.```{r}start_time=Sys.time()v=matrix(1:100000000)c=v*vend_time=Sys.time()end_time-start_time```# Packages## Install R package### Install from CRAN`install.packages()` is the standard way to install packages from CRAN.```{r}#| eval: falseinstall.packages('dplyr',repos ="http://cran.us.r-project.org")```### Install old version from CRANThe `remotes` package allows you to install specific versions of packages.```{r}#| eval: falserequire(remotes)install_version("plotly", version ="4.10.2")```### Install from GithubThe `pak` package can install packages directly from GitHub repositories.```{r}#| eval: falsepak::pkg_install("tidymodels/learntidymodels")```## Check one package version`packageVersion()` returns the version of the specified package.```{r}packageVersion("tidyverse")```## Check package location`pak::pkg_status()` provides detailed information about a package, including its installation path.```{r}pak::pkg_status("ggplot2") |>t()```## Check package dependencies`pak::pkg_deps_tree()` shows a tree of the dependencies for a given package.```{r}pak::pkg_deps_tree("tibble")```## Check all installed packages`installed.packages()` returns a matrix of all installed packages. This code filters it and displays it in an interactive table using `gt`.```{r}library(gt)ip =as.data.frame(installed.packages()[,c(1,3:4)])ip = ip[is.na(ip$Priority),1:2,drop=FALSE]ip |>gt() |>opt_interactive()```## Check currently loaded packages`.packages()` returns a character vector of the packages that are currently loaded in your R session.```{r}library(dplyr)installed_package =as.data.frame(installed.packages()[,c(1,3:4)])installed_package = installed_package[is.na(installed_package$Priority),1:2,drop=FALSE]installed_package |>filter(Package %in% (.packages()))|>gt() |>opt_interactive()```## List all packages on CRAN`available.packages()` returns a matrix of all packages available on CRAN.```{r}cran_package_num=available.packages(repos ="http://cran.us.r-project.org") |>as.data.frame()```## Check local installed old packages compared with CRAN`old.packages()` checks for installed packages that have newer versions available on CRAN.```{r}old.packages(repos ="http://cran.us.r-project.org")```## Update all installed packages`update.packages()` updates all installed packages to their latest versions.```{r}#| eval: falseupdate.packages(ask =FALSE, checkBuilt =TRUE)```## Check package install location`.libPaths()` shows the library paths where R packages are installed.```{r}.libPaths()```# Version controlThe `renv` package helps manage project-specific package libraries, making your projects more reproducible.## Initialize renv and create renv.lock with currently loaded packages`renv::init()` initializes `renv` in a project, creating a private library and a `renv.lock` file that records the package versions used.```{r}#| eval: falserenv::init()```## Update lock file`renv::snapshot()` updates the `renv.lock` file to reflect the current state of the project's library.```{r}#| eval: falserenv::snapshot()```## Make all current package versions back to the renv list`renv::restore()` restores the project library to the state recorded in `renv.lock`.```{r}#| eval: falserenv::restore()```# Stop when code runs too longThe `withTimeout()` function from the `R.utils` package runs an expression and stops it if it exceeds the specified timeout.```{r}#| warning: true#| error: truelibrary(R.utils)foo <-function() {print("Tic")for (kk in1:100) {print(kk)Sys.sleep(0.1) }print("Tac")}withTimeout({foo()}, timeout =1.5, onTimeout ="warning")```# Check website connectionThe `system()` function can run shell commands. Here, it uses `ping` to check if a website is reachable.```{r}url='www.bing.com'connect_result=system(paste0('ping -c 1 ',url))connect_result```# Using PythonThe `reticulate` package allows you to call Python from within R.## Select Python version`reticulate::py_available()` checks if Python is available, and `reticulate::py_config()` shows the Python configuration that `reticulate` is using.```{r}reticulate::py_available()``````{r}reticulate::py_config()```## Run Python in R`source_python()` executes a Python script and makes its objects available in the R environment.```{r}#| eval: falsesource_python("flights.py")``````{r, attr.output='.details summary="sessionInfo()"'}sessionInfo()```