






















Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!























We are surrounded by data every day. They can come in different shapes, formats and volumes, which need to
be stored and managed in the proper ways.
Also in business world we can find them easily, like storage and retrieval of traditional numeric and
alphanumeric data in an application developed to keep track of the number of products in stock, keeping
product number, the name, dimensions, the available quantity, etc.
Database technology is not only for traditional numeric and alphanumeric data. For example, multimedia data
such as pictures, audio, or video can also be stored in a data set. But what is a database? A database is a
collection of related data items within a specific environment (e.g., business process, university, country).
What do we mean by “related data”? Let’s consider a purchase order system; it is made up of data items about
things such as products, suppliers, and purchase orders. Each data item has specific characteristics:
These data items are both singular data and related among each other. A given product can be supplied by one
or more suppliers. A specific purchase order is connected to one supplier. A supplier can supply one or more
products. These are examples of relationships between the data items that should be adequately captured by a
database in which they are ordered, becoming meaningful information.
A collection of related data items is called a record ; a collection of them forms a database. A database
management system (DBMS) is the software package used to define, create, use, and maintain a database.
Popular DBMS suppliers are Oracle, Microsoft, IBM, and SAP, but MySQL is the most famous open-source
1
. The combination of a DBMS and a database is called a database system.
Typically, data can be classified as cross-sectional, longitudinal/time-series or panel. Cross-sectional data refer
to observations of many different objects or units of observations at a given point in time, with each observation
belonging to a different object
2
An example of cross-sectional data can be related to Italy; at the municipality level, for a given year, let us say
2010, reports some information in a collection of different data items, including, for instance, the population
of males and females, the average temperature, the GPD per capita, for each municipality
3
in the given year,
that is, 2010.
Id_firm Location Sector Size
1 Piedmont Manufacturing Small
2 Lombardy Mining Medium
3 Liguria Manufacturing Small
Let’s move on to time-series data ; they refer to many observations across time of a single unit of observation,
but each observation belongs to a different point in time. An example of this kind of data set is one referring
to the New York Stock Exchange (NYSE) and reporting daily information on average quotation prices, daily
trends, and buy and sell imbalances of a particular stock action.
1
E.g., used in applications related to storing and managing patent data sets – European Patent Office data set uses MySQL.
2
They could be firms, individuals (more specifically, workers, retired people, or students, for instance), countries (or regions,
provinces, or municipalities), patents, or stock markets.
3
In Italy they are around 8,000.
1 4 Manufacturing Female
1 4 Manufacturing Male
2 1 Trade Female
2 2 Trade Female
2 3 Trade Male
Another kind of data set of particular interest used in innovation studies is represented by (longitudinal)
matched patent-firm data. A matched patent firm data set is a data set collecting information on a given sample
of firms together with information on its patents
7
This kind of data set is useful for many reasons; the main one is that it gives the enterprise the possibility to
understand the impact of the investments in Research and Development. Famous matched patent firm data sets
are provided by ORBIS-IP (Bureau van Dijck) or can be obtained by the union of firm-level data sets and
patent data set (e.g., from the EPO, WIPO, or USPTO).
Id_firm Id_patent Sector Granted
1 1 Manufacturing Yes
1 2 Manufacturing No
1 4 Manufacturing Yes
1 4 Manufacturing No
2 1 Trade Yes
2 2 Trade Yes
2 3 Trade No
Such data can be used to answer plenty of economic and financial-related important questions. But why is it
important to answer such questions from an empirical point of view?
Because they provide a deeper understanding of the world we live in, as well as inform policy makers to
develop better strategies of intervention. For instance, from a matched employer-employee data set, a
researcher can investigate the impact of a given reform
8
or the impact of different work arrangements
9
With matched patent-firm data, a researcher may investigate several issues of interest in innovation-related
studies. For instance, one may assess the impact of developing a given set of technologies on a firm’s
performance, as well as assess which types of companies are more likely to develop certain types of advanced
technologies, like artificial intelligence.
From data sets on stock market prices, a researcher might perform forecasting analysis to predict future
developments of financial market conditions, as well as assess the impact of important macro-economic
changes on stock prices – an example is quantifying the impact of economic crises on financial markets.
7
E.g., patent number, year of application, grant status, technology field, inventor, description.
8
E.g., the introduction of less rigid employment protection legislation – EPL – provisions and its impact on worker mobility, that is,
worker turnover, hirings, and firings.
9
E.g., the use of temporary contracts or part-time arrangements and their impacts on firm productivity and profitability.
From data sets on workers and households, a researcher may assess plenty of socio-economic features and how
they might change in response to certain shocks, like what happened to wage patterns, inequality conditions,
and work-life balance outcomes during and after the pandemic.
In economics and finance, as well as in many other disciplines such as sociology, epidemiology, and
psychology, two of the most used software for data management, programming, and statistical analysis are
STATA and R, which we will explore in this course. Other software commonly used for such purposes are
MATLAB, EViews, GAUSS, and Python.
“R” is a open-source statistical software used by statisticians and economists that allows to conduct statistical
analysis, data manipulation and graphical representation. It’s free and works on all OS, capable of managing
many data and well supported by the community.
Even if it can manage large data set, when working with extremely large ones it can be a little bit difficult.
Also, learning how to use it’s difficult, needing a good effort to enter in its mechanism. Indeed, even the basic
home page is not very super-friendly.
For this reason, there are some applications, like RStudio, that make it a little bit simpler to interact with. It’s
made of different panels:
installed in other to be used.
“R” can be used also as a simple calculator, like Python, but also it’s possible to use logical operators (<, >,
>=, <=, ==, !=). But objects are the real protagonists of “R”. It can be a number, a variable, a data frame, vector
and so on.
To create them, we use the command “<-” pointing the name
10
of the object; on the other part we have the data
we want to insert in the object. In alternative, you can use the “=” sign. With this object you can perform both
calculus and compare them with logical operators.
A useful instrument to use if we have trouble is help() or ?name. If you want a general help, you simply write
command in the first manner, while if you need a hand on a specific theme, you write in quotation marks in
“R” language the command or the theme of interest or you specify it after the question mark. RStudio will
automatically open the help page on the screen.
If you don’t know the real name of the thing for “R”, you can use the command help.search(). By inserting the
theme in brackets, “R” will open a page showing all the pages in which your theme has been found. Another
possibility is to write ??theme.
10
The only rule is that it must start with a letter. Warning: “R” is case sensitive and there are some names that are blocked since they
are built-in operations, like “for” or “break”.
error if the requested package is not found, like if it is not installed. Whereas the require() command gives a
warning message and returns a logical value saying FALSE if the requested package is not found and TRUE
if the package is loaded
11
There are about 30 packages supplied with R (called “standard” and “recommended” packages) and many
more are available through the CRAN family of Internet sites.
If we need to instal a new one, you firstly have to be connected to the internet; then use the
install.packages( “package_name” ) command. Otherwise, you can go to Tools → Install new packages. To
update a package, again you have to be connected to the internet and use the update.packages( “packagename” )
command.
R works with structured data. The main categories of data structures are:
vector of length 1). Even if the program shows it in a row, the vector is saved as a column;
have two dimensions: rows and columns. Arrays are sets of numbers with p dimensions; obviously,
for p = 1 we obtain a vector, for p = 2 a matrix (in this course, we do not cover the case with p > 2);
numbers, strings, etc.). Here, elements don’t have to homogeneous, in the sense that columns don’t
have to be all of the same type, but inside of them the rule remains;
What distinguishes R from other languages is that its most basic data structure is not a single value, but is an
ordered set of values: a vector. In practice, when we create a data structure like “y <- 90” we are creating a
vector of length 1.
Vectors can gather different types of data (e.g., numbers, strings, true/false values, etc.), but all the values held
in an individual vector must be of the same type. To create a vector with more than 1 of length, we use the
function c().
It can take an arbitrary number of arguments, with them being the elements of the vector – if words are used
as data values, they must be surrounded by quotes. To save them, we have to create an object and assign to it
the vector with c(element1, element2, …).
As we did before (i.e., with numbers), you can access the whole data structure by typing its name. Otherwise,
you can use the head() command to see only the first few lines of the vector
12
. For a more graphical view, you
can use the View() – the capital V is not a typo! – command, displaying them, in RStudio, in the text editor
window.
Since we talked about data types, there are four basic data types in R:
floating-point numbers, but they are stored the same way.
For instance : num<-c( 1,2,3,4,5 ) ;
11
It is designed to be used inside functions.
12
This function is particularly helpful when the vector is long.
For instance : str<-c( “a”, “b”, “c”, “d”, “e” ) ;
For instance : logic<-c( TRUE, TRUE, FALSE, FALSE, TRUE ) ;
Factors are used when grouping data for statistical or plotting operations and in many cases are
interchangeable with characters, but there are differences (in particular, when merging or sorting data,
which can cause problems if you use the wrong type for this kind of data).
For instance : gender<-c( “F”, “M”, “F”, “F”, “M” ) produces a character vector; to transform it to a
factor vector we have to write gender.factor<-factor( gender ). This has two levels, “F” and “M”. Notice
that the values in the vector are transformed into numbers: the number 1 is associated with the category
“F”, whereas number 2 is associated with the category “M”.
To see what type of data you are storing in a vector, you can either look in the workspace panel of RStudio
(top-right panel of the figure below) or you can use the class() function.
Two functions for making vectors are particularly useful: seq() and rep(). The seq() function generates a vector
that contains a sequence of numbers based on certain rules. The basic syntax of the function is the following
is seq( from, to, by, length ) :
Note that it is not necessary to specify all the arguments. For example, once you have specified the starting
value, the final value and the increment, the length is automatically defined. Otherwise, you can specify the
starting value, the final value and the number of elements. In the first case, the length is automatically defined
by the other parameters. In the second case, the increment is automatically defined by the other parameters.
Note that, as mentioned previously, it is not necessary to specify the name of the arguments you are referring
to if you follow the default order. Instead, if you specify the name of the argument, you can write them in the
order you like. For instance, you can write seq( length=39, to=20, from=1 ). This makes more sense when
looking at larger data structures, such as our 39-element vectors just defined. You can also create a
decrementing sequence by putting a negative number in “by”.
Then, we have the rep( x, times ) function generates a vector in which an object is repeated a number of times
equal to “times”. Finally, it is possible to combine the seq() and rep() functions with c() to make up more
complicated vectors.
Some examples of it are:
increments by 2, a set of five 1s, and a decrescent sequence from 30 to 1 with decrements by 1.
To select the elements of a vector, after the name of the vector, you have to insert in square brackets a vector
of indexes indicating the position of the elements to extract. Note that, unlike other programming languages,
index counts in R start at 1 and not 0. If the index is placed with a minus sign in front, we visualize all the
element except for that one. Of course, it is possible to set conditions on elements to extract.
Factor variables can be transformed into numeric variables, using the as.integer() command. If the levels are
defined by strings (as for our gender and province variables), the transformation into numbers reflects the
alphabetical order of the levels.
To generate a data frame, we use the function data.frame(). This command allows the user to join multiple
vectors of equal length as columns of the data frame, each of which refers to a different variable
13
You might want to set different column names than those specified when creating the vectors. For instance,
suppose you want that the data frame variables are named with all-capitalized words. You simply need to write:
The str() function allows the user to analyse the structure of an object. If we ask to analyse our data frame df ,
the object class is correctly set as a data.frame. Then, you can see the list and description of each of these
variables. If you apply the names() function to the data frame, you get the names of the variables.
To see what is inside the columns/variables, you can name them or access them by position. We can either
write df[[ 1 ]] , with 1 indicating the first variable in the data frame, or df$variable_name. Each time you want
to refer to a variable within a data frame, you have to specify the name of the data frame followed by the $
symbol and then by the name of the variable you are referring to.
The above commands to see an entire column of data. However, data frames have extra functionalities to
extract subsets of data directly from within the two-dimensional structure. Specifically, the normal bracket
notation for extracting data from a vector is here extended to supply two values, identifying the rows and
columns you want to extract from a data frame.
With the command data.frame_name[ i, j ] , we extract the element in the data frame data.frame_name found in
row i and in column j. Therefore, the first index refers to the rows, while the second refers to the columns. Of
course, indexes i and j can be vectors and you can use conditions on them
14
If you do not write anything before the comma, the extraction concerns all the rows; conversely, if nothing is
written after the comma, the extraction concerns all the columns. In sum, writing the command
data.frame_name[ , j ] extracts the entire column j, that is, all the rows of the column. Instead, writing the
command data.frame_name[ i, ] extracts the whole row i, that is, all the columns for that row.
With this respect, an important note: when you are referring to a set of elements of a data frame with the
data.frame_name[ i,j ] command, you can use the column names placed in “” to refer to the relevant columns.
For instance, typing df[ , c( “age”, “gender”, “province” )] is equivalent to typing df[ , c( 1, 2, 5 )]
15
Starting from these sets of commands for data extraction, we can create other data frames based on the original
one. For data frames, it is also possible to define named rows and use these names in a similar way as for
columns. To name (or rename) columns and rows one should use the rownames() and colnames() functions.
There are some other functions that can be used with data frames. For instance, the dim() function can be used
to find out how many rows and columns the data frame has. The functions nrow() and ncol() are used to get
these values individually.
Lists are sets of R objects of different nature and size. They are often used to collect the results of an analysis
in which objects of different nature and size are stored. To generate a list, we use the list() function.
13
Note that, when creating a data frame, you have automatically a column with the indexes of observations.
14
For example, df[df$age>25,c( 3,4 )].
15
This is very useful when you are handling a big data set with many columns and don’t know the exact column number of each
variable.
After typing the above command, the objects in the list are not identified with a name, but only with a number.
Like with data frames, we can use the double square brackets to access one of the elements or with the $
symbol.
We can assign a name to each object in the list by using the names() function, in a similar way as we have seen
earlier. In practice you input a vector of strings, one for each element in the list. Importantly, you can refer to
the objects within the list by using the notation discussed earlier for vectors and for data frames.
Naming the elements within the list with multiple-word names with white spaces was not a good idea, since
this way you have to use that strange quotes that luckily R automatically suggests. You can also refer to a
whole object within a list by typing list_name[[ w ]] , where w is either the position index of the list you are
referring to or the name of the list in quotes.
Of course, it is possible to remove objects from a list. To do so, a good way when dealing with named lists, as
in our case, is to use the within() command.
In the previous lectures, we have inserted our data manually; this is usually not the case. The most common
situation is that they are inserted from external data files. R is able to read data files of virtually any format
like .txt, .csv or .tsv.
Plain-text files are the most common for storing data. Moreover, it is often possible to transform data from
other software into plaintext files. For instance, excel files can be transformed into .txt or .csv files, and the
same holds for STATA .dta files through the command “export”.
To load this type of data, we will employ the read.table() command. With the proper specifications, the
read.table() command is able to read data files with many extensions. In practice, the read.table() function
reads a table of data from a file and creates a data structure from it.
There are various options that can be set to make sure that data are imported correctly and that they are in the
required format. When using the read.table() function, you should tell “R” what the separating characters are.
Separating characters are those identifying the different values on each line of the file. Separating characters
can be commas, semicolons, or white spaces, for instance, one or more spaces and tabs
16
You can tell R this information by using the option “sep” in the read.table() function. In our case, you should
specify sep = ",", which is valid when the separator is a comma.
The default option in the read.table() function is that the data set has no column headings, so the default option
is header = FALSE. You thus need to set header = TRUE. With this option, R treats the first line of text as
column headers and not as data.
So, an example of data set information is:
df.name <- read.table(“data_set_name”, sep = “,”, header = TRUE)
17
“RStudio” provides a tool for importing data set directly from the “files” bottom left window. However, it is
much better to write directly the command to have full control of what R is doing with your text file.
16
It must be indicated as “\t” to be understood by RStudio.
17
The function takes for granted that, if we have decimals as data, they are separated by data. In case not, we would have to had to the
argument the following: dec = “,”.
NULL; but you can also use the code for accessing elements of data frames through indexes as we
have seen in the previous lectures;
variable you want to remove.
With all of the variables we have created or modified, we can perform all the operations. We can also transform
them into categorical variable that can take on multiple values. We can create the categorical variable by
using a nested set of ifelse() functions.
This function generates a dummy variable , a variable that takes the value of 1 if a certain condition is satisfied
and 0 otherwise. There are several ways to construct dummy variables. The most common way is to use the
ifelse() function:
new.variable <- ifelse( condition, value if the condition is satisfied, value if the condition is not satisfied )
Coming back to categorical variables, we could create one of them in this way:
new.variable <- ifelse( condition1, value if condition 1 is true, ifelse( condition 2, value if condition 2 is true,
ifelse( condition 3, value if condition 3 is true, ifelse( condition 4, value if condition 4 is true, value if all the
other conditions are never true ))))
From it, we can transform our new categorical variables in factor variables. To do so, we use the factor()
function. Note that we may want to rename the levels of these two factor variables, being possible with levels()
function.
This function works in a similar way as the names() function. Here, you simply apply new names to the levels.
It is possible to combine the mean() function with if conditions. To do so, we need to use the techniques for
data extractions seen in the previous lectures.
There are three main functions that we can use to work with data. The first one we see is the apply() , which
allows us to calculate a generic function on the rows or on the columns of a data matrix.
The syntax is:
apply( X, dim, FUN )
X is the data matrix; dim is the dimension along which one wants to calculate the function – option “ 1 ” stands
for “row”, option “ 2 ” stands for “column”; and FUN is the function to be applied to the data X.
Of course, the function applies to either columns or rows only if they are applicable in the specific context and
coherent with the data you want to analyse. For instance, you can’t apply the mean or median function if the
data are not quantitative.
If the variables are not homogeneous among each other, it makes no sense to carry out operations by rows, but
only by columns. A case in which applying functions by rows make sense is when you have homogeneous
variables, for instance, the grades obtained at different exams (i.e., columns) for a set of n students (i.e., rows).
In this case, if you apply, for instance, the mean() function to the rows, you obtain the average grade across the
various exams for each student. In our data set, functions by rows are not applicable since the information on
the various variables is not homogeneous.
Let’s move on to tapply() function; it is useful when you want to apply a given function separately on each
class of a qualitative variable. In other words, when you have a categorical variable, you can compute a certain
function for each category of such variable.
The syntax is:
tapply( X, index, FUN )
X is a vector
22
; index is a categorical variable, either a factor or a numerical variable, or a list of them using
the list() function; and FUN is the function to apply to the data. An example could be to calculate the mean of
the population separately for large and small provinces.
Lastly, we have the aggregate() function, which is the same as the tapply() function, but is applied to a whole
data frame rather than a single vector. The syntax will be:
aggregate( X, by, FUN )
X is a data matrix; by is a list of categorical variables, at least made up of a single variable; and FUN is the
function to apply to the data. So, in the slot for by we always have to put list() function, even if we want to sort
for only one variable.
The functions we described until now are basically useless if we talk about discrete variables. To generate
simple or double frequency distributions in R, we use the table() and prop.table() functions. Frequency
distributions are applied to categorical variables and display the frequency, either in absolute terms ( table() )
or in percentage ( prop.table() ) terms, of each possible outcome in the sample.
The first of the two accepts as argument directly the name of the variable we want to tabulate. Instead,
prop.table() function accepted argument is not the variable itself, but the tabulation in absolute numbers of it,
obtained through the table() function; so: prop.table(table( variable_name )).
To determine double frequency distributions, we again use the table() function. To do so, we simply need to
insert the list of variables. If we want to compute the relative frequency distribution, as before, we pass the
table() function as an argument of the prop.table() function. We can obtain the table of relative frequency
distribution in percentage terms by simply multiplying it by 100.
We have seen in earlier in the course that there are a number of ways to access data stored in vectors or data
frames using the square bracket notation. There is another way to access values, which we can use to create
logical data subsets.
Indeed, you can access subsets of a vector using a vector of logical values to say whether you want to include
each position or not. For example, if we create the object x , containing the numbers from 1 to 5, and the vector
logic , consisting of the list (TRUE, FALSE, FALSE, FALSE, TRUE) and we combine them together like this
x[logic] , RStudio will show only 1 and 5.
So, we can use this in combination with logical tests to filter the data. As we have seen in previous lectures, a
logical test is simply a mathematical expression that can be applied to a value to produce either a true or false
result. In R, these logical tests return a logical vector.
Their power comes out when we use the resulting logical vectors to pull out the associated data values. We can
both create a specific logical vector, or, in a shorter and much more common way, we simply put the logical
test inside the square brackets.
Obviously, these operations can all be done on data frames, computing whatever we want, including working
on specific variables belonging to them. Using logical vectors is an effective way of filtering data, since we
can compute complex commands.
When simple filtering is required, one can use the subset() function. The subset() function uses simple syntax,
so that it may be preferable to the methods described earlier. The first argument is the entire data frame, the
second argument is the subset, so a logical expression indicating the elements or rows to keep
2324
22
Note that the tapply() function accepts one vector as an argument.
23
Note that missing values are taken as false.
24
The results are printed to the screen, so that the subset() function does not modify the data frame itself. To save a filtered version of
the data set, you need to assign a name to it, as usual.
We can also plot the percentage by using prop.table() :
barplot(prop.table(table( variable_name )))
Bar plots can also be used to produce graphs with other values than the frequency of categorical variables. For
instance, we might want to create a bar plot with the averages of several (continuous) variables or a bar plot
containing the average of a variable separately for different categories of a categorical variable.
In general, we can create bar plots with whatever we want. We just need a single value to plot for each bin. To
assign a colour, we have to follow the same procedure of the one for box plots.
An alternative way to represent distributions of categorical variables is the pie chart. A pie chart is a type of
graph that displays data in a circular graph; the pieces of the graph are proportional to the fraction of the whole
in each category.
The function to generate pie charts in R is pie(). The argument must be the output of the table() function applied
to a categorical variable. The colours of the pieces of the graph can be customized as with the barplot()
function.
Of course, it is possible to customize plots with several objects, such as a title and a subtitle:
It’s now time to talk about scatter plots. A scatterplot is a Cartesian graph that allows the comparison between
two variables. It consists of the coordinates of each pair of points, which represent the value assumed by each
observation in the two variables which are being compared.
Through a scatterplot, it is possible:
to view the presence of outliers in the data, that is, of points that deviate from the “cloud of points”;
to evaluate the existence of certain relationships between the two variables, for instance, a linear or a
quadratic relationship.
The R command to produce a scatterplot is the plot() function. The basic syntax of the plot function is
plot( x, y, type = “p” )
where x and y are the two vectors (i.e., variables) that we want to consider. The vector placed in the first
position will be displayed in the x-axis, whereas the vector placed in the second position will be displayed in
the y-axis. The type argument can be omitted in this case; the “ p ” option, producing a scatterplot, is the default
value of the plot() function
28
Of course, the graph can be enriched with other arguments, such as, for example, the main option to insert a
title to the graph, or the xlab and ylab options to insert the x- and y-axis headings, respectively. It is also
possible to modify the look of the points:
It is possible to identify units on the graph with a different point shape and/or colour, depending on the value
of a categorical variable. To do so, we need to use the pch and/or col arguments. A numeric vector must be
specified for the two arguments, which allows you to associate a given point shape and/or colour to each unit,
depending on the class it belongs to.
28
We’ll see later that we’ll have to specify it when we want to produce a line graph.
Note that if the classification variable is a vector of strings, it must be transformed into a numeric vector first,
by using the as.integer() function. As for factor variables, you should also transform them into numeric vectors
if you want to use them within the pch argument.
Since this possibility, it is useful to add a legend to our graph, in order to distinguish the different colours/shapes
of the points. To do so, we need to use the legend() function, which has to be inserted after the plot() function.
The basic syntax is the following:
legend( x, y, legend )
Here, x and y are the coordinates of x and y axis at which the legend is placed, while legend is a vector, of the
same length as the number of different classes in the classification variable, which represents the various
elements to be identified.
Note that the legend can be positioned using keywords rather than coordinates (e.g., "bottomleft", "topright",
"center"). If we are happy with the names associated with each class of our factor variable, we can directly use
the levels() function to get and give the names of the classes.
In general, however, we construct a vector with the names of the classes of the categorical variable to be
attached. Finally, we need to associate to each element in the string vector (i.e., with the names of each class)
the corresponding symbol, through the pch and col options.
Lastly, we have line graphs ; they are a variation of the scatter plot function. A line graph is a graph that uses
lines to connect individual data points that, typically, display quantitative values over a specified time interval.
While line graphs are used for different purposes, their most common function is to create a graphical depiction
of changes in values over time. The syntax is the same as the scatter plot one, using the plot() function, except
that now you must indicate the typology of the graph with the type option to be “l”, which stands for “line”.
Note that the lwd option sets the width of the line. There are plenty of options that you can select to customize
your graphs, that are the same we have seen for the other types.
Graphs can be exported from RStudio using the item Export from the menu bar in the graphics window. The
graph can be saved as a pdf or as a range of image formats.
Up to now we have seen some basic and very useful functions of R. However, we might need some more
complicated techniques to solve more complex problems. For example, how can we spot if in our data set we
have duplicates?
Detecting repeated values in a vector, or variable within a data frame, is a simple operation, which can be
useful on its own. Executing such an operation in combination with selection can be used to deduplicate
complex data structures.
Two functions allow you to deal with duplication:
The duplicated() function takes a vector of values and returns a logical vector, which says if each item in the
vector is a duplicate of one which has already been seen earlier in that vector.
To sort a data set, it is strongly recommended to use the order() function, as it is more flexible and allows for
more complicated uses in the context of data frames. This is because it provides a vector of indices, which can
be used in conjunction with the square bracket notation.
Another important operation that can be used to sort/sift is the is.na() function. This function allows you to
find NA values within a vector.
Set operations allow combining data in two vectors, which might be needed in data analysis. R has a number
of functions and operators which relate to combining vectors, among which, we look at:
The %in% operator is a built-in part of the R language, which deals with combining vectors. This operator
underlies the code behind many other set-based functions. This operator is put between two vectors and returns
a logical vector of the same length as the first vector, where TRUE or FALSE values depend on whether the
value at each position in the first vector was present anywhere in the second vector
For instance, if we define two vectors containing homogeneous information, like the ages of individuals, by
using the %in% operator, we can see which elements of the first vector are also present in the second one.
Moving on, the intersect() function takes in two vectors, not necessarily homogeneous, and returns a vector of
the values which are present in both of them. On the other hand, the setdiff() function takes in two vectors and
returns the subset of the first vector whose values do not appear in the second vector.
Stata is a powerful, integrated statistical software package widely used by researchers, particularly in fields
like economics, sociology, political science, and public health. Created in 1985, it provides a comprehensive
set of tools for data management, statistical analysis, and high-quality graphics.
Stata's flexibility allows users to perform tasks ranging from simple data description to complex modelling
techniques, such as survival analysis, time series analysis, and panel data models.
One of Stata's defining features is its command-line interface, which ensures reproducibility and allows for
complex scripting, although it also offers a full graphical user interface for users who prefer menus.
This dual approach makes it accessible for beginners while providing the depth required by advanced
researchers. Its robust data management capabilities and extensive library of user-written programs (add-ons)
further solidify its position as a standard tool for empirical research and data analysis. Moreover, with Stata
you can communicate with other programming languages, like C++, Python, GitHub and Java.
The working environment is composed of five windows:
We can also open specific windows by clicking on icons; the most common and used ones are the ones in the
table here on the left. Many software functionalities are available from the dropdown menus. They are very
useful when you are unsure of commands
to run or unfamiliar with available
options. Indeed, every command issued in
this manner is echoed to the review and
results windows.
To explore data, we can either use the two
first commands on the left or use one of
the following functions:
spreadsheet format, looking very similar to Excel;
o How many observations (rows) and variables (columns) you have;
o The Variable Name;
o The Storage Type (e.g., str for text, float/int for numbers);
o The Variable Label.
all of them or make STATA show part of them. For example:
o list varlist1 varlist2 : it displays only the columns for varlist1 and varlist2 ;
o list in 1/10 : displays only the first 10 rows;
o list if varlist1 <75 : it shows only the observations where varlist1 is lower than 75.
The data type that STATA supports are the following:
o byte – integer in the range (- 12 7, 100 );
o int – integer in the range (- 32 ’ 767 , 32 ’ 740 );