Введення до R
Last updated on 2026-01-17 | Edit this page
Overview
Questions
- Які типи даних доступні в R?
- Що таке об’єкт?
- Як можна присвоювати іменам об’єкти різних типів даних?
- Які арифметичні та логічні оператори можна використовувати?
- Як можна отримати підмножини з векторів?
- Як в R трактувати відсутні значення?
- Як ми можемо впоратися з відсутніми значеннями в R?
Objectives
- Визначити такі терміни, як вони стосуються R: об’єкт, призначення, виклик, функція, аргументи, параметри.
- Призначити значення іменам у R.
- Дізнатися, як називати об’єкти.
- Використовувати коментарі для інформування сценарію.
- Розв’язувати прості арифметичні операції в R.
- Викликати функції та використовувати аргументи, щоб змінити їх параметри за замовчуванням.
- Оглянути вміст векторів і маніпулювати їх вмістом.
- Значення підмножини з векторів.
- Аналізувати вектори з відсутніми даними.
Створення об’єктів в R
Ви можете використовувати R для простих математичних обчислень, друкуючи формули у консолі:
R
3 + 5
OUTPUT
[1] 8
R
12 / 7
OUTPUT
[1] 1.714286
Все, що існує в R - це об’єкти: від простих числових
значень та рядків до складніших об’єктів, таких як вектори, матриці та
списки. Навіть вирази й функції є об’єктами в R.
Однак, щоб робити корисні та цікаві речі, нам потрібно звертатися до
об’єктів. Для цього нам потрібно вказати ім’я, за яким слідує
оператор присвоєння <-, і об’єкт, який ми
хочемо назвати:
R
areaHectares <- 1.0
<- - оператор присвоєння. Він призначає значення
(об’єкти) праворуч іменам (також званим символами) на ліворуч.
Отже, після виконання x <- 3 значення x
дорівнює 3. Стрілку можна прочитати як 3 переходить
в x. З історичних причин ви також можете
використовувати = для присвоєння, але не в кожному
контексті. Через незначні
відмінності у синтаксисі, рекомендується завжди використовувати
<- для присвоєння. Більше загалом ми віддаємо перевагу
синтаксису <- перед =, оскільки він дає
зрозуміти, в якому напрямку працює призначення (ліве призначення), і це
збільшує читабельність коду.
У RStudio ввівши Alt + - (натискайте
Alt одночасно з клавішею -) запише
<- за допомогою лише однієї комбінації швидких клавіш у
Windows. На Mac, те ж саме можна зробити, вводячи Option +
- (натискайте Option одночасно з клавішею
-).
Об’єктам можна дати будь-яку назву, наприклад x,
current_temperature або subject_id. Ви хочете,
щоб ваші назви об’єктів були явними й не надто довгими. Вони не можуть
починатися з числа (2x не є дійсним, але x2
є). R чутливий до регістру (наприклад, age відрізняється
від Age). Є деякі назви, які не можна використовувати,
оскільки вони є назвами фундаментальних об’єктів у R (наприклад,
if, else, for, див. тут
для повного списку). Загалом, навіть якщо це дозволено, краще не
використовувати їх (наприклад, c, T,
mean, data, df,
weights). Якщо ви сумніваєтесь, перевірте довідку, щоб
побачити, чи ім’я вже використовується. Також краще уникати крапок
(.) у назві об’єкта, як у my.dataset. Існує
багато об’єктів в R з крапками в назвах з історичних причин, але
оскільки точки мають особливе значення в R (для методів) та інших мовах
програмування, краще уникати їх. Рекомендований стиль написання
називається snake _case, що передбачає використання лише малих літер та
цифр та розділення кожного слова підкресленням (наприклад,
animal _weight, average _income). Також рекомендується використовувати
іменники для назв об’єктів, а дієслова для назв функцій. Важливо бути
послідовним у стилізації вашого коду (де ви розміщуєте пробіли, як ви
називаєте об’єкти тощо). Використання послідовного стилю кодування
робить ваш код зрозумілішим для читання для вас та ваших співробітників.
У R три популярні посібники зі стилю: Google, Jean
Fan’s та tidyverse. Tidyverse
дуже вичерпний і спочатку може здатися приголомшливим. Ви можете
встановити пакет lintr,
щоб автоматично перевіряти на наявність проблем у стилі вашого коду.
Об’єкти проти змінних
Іменування об’єктів у R якось пов’язане з
змінними у багатьох інших мовах програмування. У багатьох
мовах програмування змінна має три аспекти: ім’я, місце розташування
пам’яті та поточне значення, що зберігається в цьому місці.
R абстракції з модифікованих місць пам’яті. У
R ми маємо лише об’єкти, які можна назвати. Залежно від
контексту name (of a object)і variable можуть
мати різко різні значення. Однак у цьому уроці два слова
використовуються як синоніми. Для отримання додаткової інформації див.:
https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects
При присвоюванні значення назви, R не друкує нічого. Ви можете змусити R надрукувати значення за допомогою дужок або ввівши назву об’єкта:
R
area_hectares <- 1.0 # не виводить нічого
(area_hectares <- 1.0) # якщо взяти вираз у дужки — він надрукує значення `area_hectares`
OUTPUT
[1] 1
R
area_hectares # друкує значення також, якщо просто ввести назву об’єкта
OUTPUT
[1] 1
Тепер, коли R має area_hectares в пам’яті, ми можемо
робити з ним арифметичні операції. Наприклад, ми можемо захотіти
перетворити цю площу на гектари (площа в акрах дорівнює 2,47 р. більше
площі в гектарах):
R
2.47 * area_hectares
OUTPUT
[1] 2.47
Ми також можемо змінити значення, присвоєне імені, призначивши йому нове:
R
area_hectares <- 2.5
2.47 * area_hectares
OUTPUT
[1] 6.175
Це означає, що присвоєння значення одному імені не змінює значення
інших імен. Наприклад, назвемо площу ділянки в акрах
areaAcres:
R
area_acres <- 2.47 * area_hectares
потім змінити (перепризначити) area_hectares на 50.
R
area_hectares <- 50
Завдання
Як ви думаєте, яке поточне значення area_acres? 123.5
або 6.175?
The value of area_acres is still 6.175 because you have
not re-run the line area_acres <- 2.47 * area_hectares
since changing the value of area_hectares.
Comments
All programming languages allow the programmer to include comments in their code. Including comments to your code has many advantages: it helps you explain your reasoning and it forces you to be tidy. A commented code is also a great tool not only to your collaborators, but to your future self. Comments are the key to a reproducible analysis.
To do this in R we use the # character. Anything to the
right of the # sign and up to the end of the line is
treated as a comment and is ignored by R. You can start lines with
comments or include them after any code on the line.
R
area_hectares <- 1.0 # land area in hectares
area_acres <- area_hectares * 2.47 # convert to acres
area_acres # print land area in acres.
OUTPUT
[1] 2.47
RStudio makes it easy to comment or uncomment a paragraph: after selecting the lines you want to comment, press at the same time on your keyboard Ctrl + Shift + C. If you only want to comment out one line, you can put the cursor at any location of that line (i.e. no need to select the whole line), then press Ctrl + Shift + C.
Exercise
Create two variables r_length and r_width
and assign them values. It should be noted that, because
length is a built-in R function, R Studio might add “()”
after you type length and if you leave the parentheses you
will get unexpected results. This is why you might see other programmers
abbreviate common words. Create a third variable r_area and
give it a value based on the current values of r_length and
r_width. Show that changing the values of either
r_length and r_width does not affect the value
of r_area.
R
r_length <- 2.5
r_width <- 3.2
r_area <- r_length * r_width
r_area
OUTPUT
[1] 8
R
# change the values of r_length and r_width
r_length <- 7.0
r_width <- 6.5
# the value of r_area isn't changed
r_area
OUTPUT
[1] 8
Functions and their arguments
Functions are “canned scripts” that automate more complicated sets of
commands including operations assignments, etc. Many functions are
predefined, or can be made available by importing R packages
(more on that later). A function usually gets one or more inputs called
arguments. Functions often (but not always) return a
value. A typical example would be the function
sqrt(). The input (the argument) must be a number, and the
return value (in fact, the output) is the square root of that number.
Executing a function (‘running it’) is called calling the
function. An example of a function call is:
R
b <- sqrt(a)
Here, the value of a is given to the sqrt()
function, the sqrt() function calculates the square root,
and returns the value which is then assigned to the name b.
This function is very simple, because it takes just one argument.
The return ‘value’ of a function need not be numerical (like that of
sqrt()), and it also does not need to be a single item: it
can be a set of things, or even a dataset. We’ll see that when we read
data files into R.
Arguments can be anything, not only numbers or filenames, but also other objects. Exactly what each argument means differs per function, and must be looked up in the documentation (see below). Some functions take arguments which may either be specified by the user, or, if left out, take on a default value: these are called options. Options are typically used to alter the way the function operates, such as whether it ignores ‘bad values’, or what symbol to use in a plot. However, if you want something specific, you can specify a value of your choice which will be used instead of the default.
Let’s try a function that can take multiple arguments:
round().
R
round(3.14159)
OUTPUT
[1] 3
Here, we’ve called round() with just one argument,
3.14159, and it has returned the value 3.
That’s because the default is to round to the nearest whole number. If
we want more digits we can see how to do that by getting information
about the round function. We can use
args(round) or look at the help for this function using
?round.
R
args(round)
OUTPUT
function (x, digits = 0, ...)
NULL
R
?round
We see that if we want a different number of digits, we can type
digits=2 or however many we want.
R
round(3.14159, digits = 2)
OUTPUT
[1] 3.14
If you provide the arguments in the exact same order as they are defined you don’t have to name them:
R
round(3.14159, 2)
OUTPUT
[1] 3.14
And if you do name the arguments, you can switch their order:
R
round(digits = 2, x = 3.14159)
OUTPUT
[1] 3.14
It’s good practice to put the non-optional arguments (like the number you’re rounding) first in your function call, and to specify the names of all optional arguments. If you don’t, someone reading your code might have to look up the definition of a function with unfamiliar arguments to understand what you’re doing.
Exercise
Type in ?round at the console and then look at the
output in the Help pane. What other functions exist that are similar to
round? How do you use the digits parameter in
the round function?
Vectors and data types
A vector is the most common and basic data type in R, and is pretty
much the workhorse of R. A vector is composed by a series of values,
which can be either numbers or characters. We can assign a series of
values to a vector using the c() function. For example we
can create a vector of the number of household members for the
households we’ve interviewed and assign it to
hh_members:
R
hh_members <- c(3, 7, 10, 6)
hh_members
OUTPUT
[1] 3 7 10 6
A vector can also contain characters. For example, we can have a
vector of the building material used to construct our interview
respondents’ walls (respondent_wall_type):
R
respondent_wall_type <- c("muddaub", "burntbricks", "sunbricks")
respondent_wall_type
OUTPUT
[1] "muddaub" "burntbricks" "sunbricks"
The quotes around “muddaub”, etc. are essential here. Without the
quotes R will assume there are objects called muddaub,
burntbricks and sunbricks. As these names
don’t exist in R’s memory, there will be an error message.
There are many functions that allow you to inspect the content of a
vector. length() tells you how many elements are in a
particular vector:
R
length(hh_members)
OUTPUT
[1] 4
R
length(respondent_wall_type)
OUTPUT
[1] 3
An important feature of a vector, is that all of the elements are the
same type of data. The function typeof() indicates the type
of an object:
R
typeof(hh_members)
OUTPUT
[1] "double"
R
typeof(respondent_wall_type)
OUTPUT
[1] "character"
The function str() provides an overview of the structure
of an object and its elements. It is a useful function when working with
large and complex objects:
R
str(hh_members)
OUTPUT
num [1:4] 3 7 10 6
R
str(respondent_wall_type)
OUTPUT
chr [1:3] "muddaub" "burntbricks" "sunbricks"
You can use the c() function to add other elements to
your vector:
R
possessions <- c("bicycle", "radio", "television")
possessions <- c(possessions, "mobile_phone") # add to the end of the vector
possessions <- c("car", possessions) # add to the beginning of the vector
possessions
OUTPUT
[1] "car" "bicycle" "radio" "television" "mobile_phone"
In the first line, we take the original vector
possessions, add the value "mobile_phone" to
the end of it, and save the result back into possessions.
Then we add the value "car" to the beginning, again saving
the result back into possessions.
We can do this over and over again to grow a vector, or assemble a dataset. As we program, this may be useful to add results that we are collecting or calculating.
An atomic vector is the simplest R data
type and is a linear vector of a single type. Above, we saw 2
of the 6 main atomic vector types that R uses:
"character" and "numeric" (or
"double"). These are the basic building blocks that all R
objects are built from. The other 4 atomic vector types
are:
-
"logical"forTRUEandFALSE(the boolean data type) -
"integer"for integer numbers (e.g.,2L, theLindicates to R that it’s an integer) -
"complex"to represent complex numbers with real and imaginary parts (e.g.,1 + 4i) and that’s all we’re going to say about them -
"raw"for bitstreams that we won’t discuss further
You can check the type of your vector using the typeof()
function and inputting your vector as the argument.
Vectors are one of the many data structures that R
uses. Other important ones are lists (list), matrices
(matrix), data frames (data.frame), factors
(factor) and arrays (array).
Exercise
We’ve seen that atomic vectors can be of type character, numeric (or double), integer, and logical. But what happens if we try to mix these types in a single vector?
R implicitly converts them to all be the same type.
Exercise (continued)
What will happen in each of these examples? (hint: use
class() to check the data type of your objects):
R
num_char <- c(1, 2, 3, "a")
num_logical <- c(1, 2, 3, TRUE)
char_logical <- c("a", "b", "c", TRUE)
tricky <- c(1, 2, 3, "4")
Why do you think it happens?
Vectors can be of only one data type. R tries to convert (coerce) the content of this vector to find a “common denominator” that doesn’t lose any information.
Exercise (continued)
How many values in combined_logical are
"TRUE" (as a character) in the following example:
R
num_logical <- c(1, 2, 3, TRUE)
char_logical <- c("a", "b", "c", TRUE)
combined_logical <- c(num_logical, char_logical)
Only one. There is no memory of past data types, and the coercion
happens the first time the vector is evaluated. Therefore, the
TRUE in num_logical gets converted into a
1 before it gets converted into "1" in
combined_logical.
Exercise (continued)
You’ve probably noticed that objects of different types get converted into a single, shared type within a vector. In R, we call converting objects from one class into another class coercion. These conversions happen according to a hierarchy, whereby some types get preferentially coerced into other types. Can you draw a diagram that represents the hierarchy of how these data types are coerced?
Subsetting vectors
Subsetting (sometimes referred to as extracting or indexing) involves accessing out one or more values based on their numeric placement or “index” within a vector. If we want to subset one or several values from a vector, we must provide one index or several indices in square brackets. For instance:
R
respondent_wall_type <- c("muddaub", "burntbricks", "sunbricks")
respondent_wall_type[2]
OUTPUT
[1] "burntbricks"
R
respondent_wall_type[c(3, 2)]
OUTPUT
[1] "sunbricks" "burntbricks"
We can also repeat the indices to create an object with more elements than the original one:
R
more_respondent_wall_type <- respondent_wall_type[c(1, 2, 3, 2, 1, 3)]
more_respondent_wall_type
OUTPUT
[1] "muddaub" "burntbricks" "sunbricks" "burntbricks" "muddaub"
[6] "sunbricks"
R indices start at 1. Programming languages like Fortran, MATLAB, Julia, and R start counting at 1, because that’s what human beings typically do. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because that’s simpler for computers to do.
Conditional subsetting
Another common way of subsetting is by using a logical vector.
TRUE will select the element with the same index, while
FALSE will not:
R
hh_members <- c(3, 7, 10, 6)
hh_members[c(TRUE, FALSE, TRUE, TRUE)]
OUTPUT
[1] 3 10 6
Typically, these logical vectors are not typed by hand, but are the output of other functions or logical tests. For instance, if you wanted to select only the values above 5:
R
hh_members > 5 # will return logicals with TRUE for the indices that meet the condition
OUTPUT
[1] FALSE TRUE TRUE TRUE
R
## so we can use this to select only the values above 5
hh_members[hh_members > 5]
OUTPUT
[1] 7 10 6
You can combine multiple tests using & (both
conditions are true, AND) or | (at least one of the
conditions is true, OR):
R
hh_members[hh_members < 4 | hh_members > 7]
OUTPUT
[1] 3 10
R
hh_members[hh_members >= 4 & hh_members <= 7]
OUTPUT
[1] 7 6
Here, < stands for “less than”, > for
“greater than”, >= for “greater than or equal to”, and
== for “equal to”. The double equal sign == is
a test for numerical equality between the left and right hand sides, and
should not be confused with the single = sign, which
performs variable assignment (similar to <-).
A common task is to search for certain strings in a vector. One could
use the “or” operator | to test for equality to multiple
values, but this can quickly become tedious.
R
possessions <- c("car", "bicycle", "radio", "television", "mobile_phone")
possessions[possessions == "car" | possessions == "bicycle"] # returns both car and bicycle
OUTPUT
[1] "car" "bicycle"
The function %in% allows you to test if any of the
elements of a search vector (on the left hand side) are found in the
target vector (on the right hand side):
R
possessions %in% c("car", "bicycle")
OUTPUT
[1] TRUE TRUE FALSE FALSE FALSE
Note that the output is the same length as the search vector on the
left hand side, because %in% checks whether each element of
the search vector is found somewhere in the target vector. Thus, you can
use %in% to select the elements in the search vector that
appear in your target vector:
R
possessions %in% c("car", "bicycle", "motorcycle", "truck", "boat", "bus")
OUTPUT
[1] TRUE TRUE FALSE FALSE FALSE
R
possessions[possessions %in% c("car", "bicycle", "motorcycle", "truck", "boat", "bus")]
OUTPUT
[1] "car" "bicycle"
Missing data
As R was designed to analyze datasets, it includes the concept of
missing data (which is uncommon in other programming languages). Missing
data are represented in vectors as NA.
When doing operations on numbers, most functions will return
NA if the data you are working with include missing values.
This feature makes it harder to overlook the cases where you are dealing
with missing data. You can add the argument na.rm=TRUE to
calculate the result while ignoring the missing values.
R
rooms <- c(2, 1, 1, NA, 7)
mean(rooms)
OUTPUT
[1] NA
R
max(rooms)
OUTPUT
[1] NA
R
mean(rooms, na.rm = TRUE)
OUTPUT
[1] 2.75
R
max(rooms, na.rm = TRUE)
OUTPUT
[1] 7
If your data include missing values, you may want to become familiar
with the functions is.na(), na.omit(), and
complete.cases(). See below for examples.
R
## Extract those elements which are not missing values.
## The ! character is also called the NOT operator
rooms[!is.na(rooms)]
OUTPUT
[1] 2 1 1 7
R
## Count the number of missing values.
## The output of is.na() is a logical vector (TRUE/FALSE equivalent to 1/0) so the sum() function here is effectively counting
sum(is.na(rooms))
OUTPUT
[1] 1
R
## Returns the object with incomplete cases removed. The returned object is an atomic vector of type `"numeric"` (or `"double"`).
na.omit(rooms)
OUTPUT
[1] 2 1 1 7
attr(,"na.action")
[1] 4
attr(,"class")
[1] "omit"
R
## Extract those elements which are complete cases. The returned object is an atomic vector of type `"numeric"` (or `"double"`).
rooms[complete.cases(rooms)]
OUTPUT
[1] 2 1 1 7
Recall that you can use the typeof() function to find
the type of your atomic vector.
Exercise
- Using this vector of rooms, create a new vector with the NAs removed.
R
rooms <- c(1, 2, 1, 1, NA, 3, 1, 3, 2, 1, 1, 8, 3, 1, NA, 1)
Use the function
median()to calculate the median of theroomsvector.Use R to figure out how many households in the set use more than 2 rooms for sleeping.
R
rooms <- c(1, 2, 1, 1, NA, 3, 1, 3, 2, 1, 1, 8, 3, 1, NA, 1)
rooms_no_na <- rooms[!is.na(rooms)]
# or
rooms_no_na <- na.omit(rooms)
# 2.
median(rooms, na.rm = TRUE)
OUTPUT
[1] 1
R
# 3.
rooms_above_2 <- rooms_no_na[rooms_no_na > 2]
length(rooms_above_2)
OUTPUT
[1] 4
Now that we have learned how to write scripts, and the basics of R’s data structures, we are ready to start working with the SAFI dataset we have been using in the other lessons, and learn about data frames.
- Access individual values by location using
[]. - Access arbitrary sets of data using
[c(...)]. - Use logical operations and logical vectors to access subsets of data.