Programming Features

Last updated: January 18, 2021

This page is is a list of miscellaneous “programming” features in R.

For loops

names <- c("a", "b", "c")
for (name in names) {
    print(name)
}

Extracting parts of an object

> c(abc=123)
abc
123
> c(abc=123)[[1]]
[1] 123
> c(abc=123)[1]
abc
123

For more information type ?"[[" into R.

Assigning and calling objects with dynamically defined names

name_for_object <- "foo"
value_for_object <- c(1,2,3)
assign(name_for_object, value_for_object)

print(foo)
# [1] 1 2 3

print(get(name_for_object))
# [1] 1 2 3

Built-in datasets

Run data() to see all the available built-in datsets of sample data.

Alternative console

Radian is an ipython-like replacement for the standard R console. It adds syntax highlighting, reticulate support for Python integration, multi-line editing, and a bunch of other nice stuff.

Language features added by tidyverse

Pipes

The main pipe operator is %>%, which can be inserted with cmd-shift-m in RStudio.

When working with pipes, you may also need to use the . placeholder:

> CO2 %>% head(10)
   Plant   Type  Treatment conc uptake
1    Qn1 Quebec nonchilled   95   16.0
2    Qn1 Quebec nonchilled  175   30.4
3    Qn1 Quebec nonchilled  250   34.8
4    Qn1 Quebec nonchilled  350   37.2
5    Qn1 Quebec nonchilled  500   35.3
6    Qn1 Quebec nonchilled  675   39.2
7    Qn1 Quebec nonchilled 1000   39.7
8    Qn2 Quebec nonchilled   95   13.6
9    Qn2 Quebec nonchilled  175   27.3
10   Qn2 Quebec nonchilled  250   37.1

> CO2 %>% head(10) %>% .$uptake
 [1] 16.0 30.4 34.8 37.2 35.3 39.2 39.7 13.6 27.3 37.1

> CO2 %>% head(10) %>% .[['uptake']]
 [1] 16.0 30.4 34.8 37.2 35.3 39.2 39.7 13.6 27.3 37.1

ℹī¸ This page is part of my knowledge base for R, the popular statistical programming language. I attempt to use idiomatic practices with the tidyverse collection of packages as much as possible. If you have suggestions for ways to improve this code, please contact me or use the survey link below..