0% found this document useful (0 votes)
13 views41 pages

1100 01 R Intro Video

Uploaded by

hinching612186
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views41 pages

1100 01 R Intro Video

Uploaded by

hinching612186
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Installing R & RStudio RStudio R Conclusion

R and RStudio
Dr. ZHOU Titi
Division of Social Science
HKUST

SOSC 1100: Quantitative Data Analysis for Social Research I

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 0/40
Installing R & RStudio RStudio R Conclusion

Plan for Today

! How to install R and RStudio?


! Become familiar with RStudio What we cando
! Become familiar with R
! Do calculations: +, −, ∗, /, ˆ
! Create objects: <-
! Working with vectors: c(), [ ], " ", =, ==
creat ⼩
的 orm

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 1/40
Installing R & RStudio RStudio R Conclusion

Why R?

! A bad idea to analyze data in a "point and click" spreadsheet (e.g.,


Microsoft Excel).

J Rcabopeeudeand
! Very limited in terms of what analyses they allow you to do.
! Not facilitate robust and reproducible practices. ,
E7 X
Khem how to Ereate amad use the data
! A very good idea to avoid proprietary software. result
yMath
! While glossy and powerful, they are also very expensive.
! R: open-source, freely available for Windows, Mac and Linux.

! R is highly extensible and flexible.


! Lots of people write their own packages that extent the system, and these
are freely available.
! A lot of advanced textbooks on data analysis nowadays use R. ⇒ Better help
you to become a genuine expert in data analysis.

! As you get better at using R, you’re also learning to program.


! Programming is a core skill in today’s digital era.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 2/40
Installing R & RStudio RStudio R Conclusion

Installing R

How to install R?

! Download at http://cran.r-project.org/.

! Separate links for Windows, Mac and Linux users.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 3/40
Installing R & RStudio RStudio R Conclusion

Installing R

To install R on Windows (link)

1 "Download R for Window" to a page that offers a few options:


! Click "install R for the first time" at the top, or "base" to its left
2 On the new page, download the installer program:
! Click the link at the top: something like "Download R-4.2.2 for Windows"
except the "4.2.2" will be replaced by the latest version of R.
3 Run the installer program and step through the installation wizard.
! The default will be suitable for most users, so just click through.
! The wizard will install R into your program files folders and place a shortcut
in your Start menu.
! Make sure you have all of the appropriate administration privileges to install
new software on your computer.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 4/40
Installing R & RStudio RStudio R Conclusion

Installing R

To install R on Mac (link)

1 "Download R for Mac" ⇒ click "R-4.2.2.pkg" to download the installer file.


! Be sure about the version of your operating system: Mac OS X 10.6 (Snow
Leopard) or higher
! If you have an M1 or higher Macs, you may choose to download
"R-4.2.2-arm64.pkg".
2 Run the installer and step through the installation process.
! While you are allowed to customize your installation, just follow the defaults.
! If you Mac requires a password for installing new programs, you need it here.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 5/40
Installing R & RStudio RStudio R Conclusion

Installing R

To install R on Linux (link)

! R comes preinstalled on many Linux systems, but you’ll want the latest
version.
! "Download R for Linux" ⇒ files to build R from source on Debian, Redhat,
SUSE, and Ubuntu systems.
! The installation procedure varies with the Linux system you use.
! CRAN provides separate instructions by grouping each set of source files with
documentation or README files that explain how to install on your system.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 6/40
Installing R & RStudio RStudio R Conclusion

Installing R

Testing R

! Double-click (Windows or Mac)


or type R into the Console (Linux),
you will see R Console.
! Type R commands into the
Console after the command
prompt > | , and press ENTER.

plot(1:10)

! Output: A plot of the numbers 1


to 10 on both the x and y axes

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 7/40
Installing R & RStudio RStudio R Conclusion

Installing RStudio

Why RStudio?

! A popular Integrated Development Environment (IDE).


! Like Microsoft Word that helps you write in English, RStudio provides a
user-friendly interface to write in R.
! Incorporate the R Console, a script editor and other useful functionality (e.g.
R markdown and Git Hub integration).
USPDFsshare Your code
! Open-source and freely available
! The interface looks the same for Windows, Mac OS, and Linux, and helps
me match the lecture to your personal experience.
! There are lots of instructions freely available online.

! We will always start by opening RStudio, which will open R by itself.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 8/40
Installing R & RStudio RStudio R Conclusion

Installing RStudio

How to install RStudio?

! Click the "Download RStudio" button at the RStudio website.


! Choose "RStudio Desktop" and click "Download RStudio":
! For Windows and Mac users, you will see the appropriate link for
downloading. If not, scroll down to the "All Installers" section and choose
the link manually.
! For Linux users, scroll down to the "All Installers" section and choose the
appropriate link to download the binary for your system. RStudio for Ubuntu
(and Debian) is available as a *.deb package.

! Once installed, you can open it ( ) like any other program on your
computer.
! Note: you must install R before you install RStudio.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 9/40
Installing R & RStudio RStudio R Conclusion

Updating R and RStudio

How to update R?

! Usually issue updates every six months. Find the latest version to download.

1 One way is to run the R program ( ):


! Go to the "R" menu at the top and click "Check for R Updates".
! R will tell you the current version and whether or not you may need to
download a newer version.

2 In RStudio, type and run sessionInfo() in the R Console.


! The first line it returns shows the version of R that you are using.
! If there is a newer version available, you can then download it at
https://cran.r-project.org/.

! For Windows users, you may need to uninstall R to update it. You can find
a quick guide here.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 10/40
Installing R & RStudio RStudio R Conclusion

Updating R and RStudio

How to update RStudio?

1 Click "Help" on the top menu bar ⇒ click "Check for Updates".

2 Quit RStudio, then visit the RStudio website to download.

3 Install the latest version.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 11/40
Installing R & RStudio RStudio R Conclusion

RStudio orientation

! When you start RStudio for the first time, you’ll see three panels:

! You can customize the location of each pane:


! Click the "Tools" menu at the top ⇒ Global Options ⇒ Pane Layout.
! There are more ways to customize RStudio (link).
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 12/40
Installing R & RStudio RStudio R Conclusion

Console

Console

! Just like what we do in application.


! You can type some code at the console (click on the part where the cursor
is > | ) and when you press ENTER, R will run that code.
! If you type 2 + 2 into the Console, you should obtain the answer 4 .

! What does [1] mean? For now, you can think of it as if R were saying "the
answer to the 1st question you asked is 4".
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 13/40
Installing R & RStudio RStudio R Conclusion

Console

Formatting in our lecture slides

! In the lecture slides, code and its output will be presented in a way that is
different from what you will see in the Console.
! In your Console, you type after the > , but the code in our slides will not
contain this command prompt.
! In your Console, output appears directly after your code, while in the slides,
it is commented out with ## .

In your Console: In our slides:


> 20 + 5 20 + 5
[1] 25 ## [1] 25

! To let you be able to copy code from the slides directly into R for testing.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 14/40
Installing R & RStudio RStudio R Conclusion

Console

Careful to avoid typos

! R is "stupid" because it cannot handle typos.


! Suppose that you forgot to hit the shift key when trying to type +, and as
result your code ended up being 10 = 20 rather than 10 + 20.

10 = 20
## Error in 10 = 20: invalid (do_set) left-hand side to assignment

! We human know that + and = are on the same key.


! From R’s perspective, 10, 20 and = are all legitimate and this is exactly what
the user meant.
! R can only "discover" that the code is nonsense when it tries to follow your
instruction.

! R is mindlessly obedient and can only do exactly what you ask it to do.
You absolutely must be precise in what you say to R.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 15/40
Installing R & RStudio RStudio R Conclusion

Console

An exception: A bit flexible with spacing

! R ignores redundant spacing: 10+20 is equivalent to 10 + 20


! But not always: e.g., to add space in the middle of the word or the
operator.
! citation() = citation () = citation( ) , but $= citat ion()

citat ion()
## Error: unexpected symbol in "citat ion"

! x<-3 = x <-3 = x<- 3 = x <- 3 $= x < - 3

x < - 3 ## [1] FALSE

! Try to be consistent in writing your code.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 16/40
Installing R & RStudio RStudio R Conclusion

Scripts

Scripts edier
! The Console is great for simple tasks but not for projects with a lot of code.
! R script: a plain text file with a .R file extension
! It stores your lines of R code and allows you to edit. save thecode
! The lines of code are to be sourced into the R Console line by line.
! ALWAYS work from a script file in this class.
! To create a new script, use the menu or the toolbar button as shown below.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 17/40
Installing R & RStudio RStudio R Conclusion

Scripts

Now you have a new window (called the Source pane) in the top left of RStudio.
! The new window is a script editor and where you will write your code.
! The Console is now in the bottom left.

! Once you’ve created a script, give it a name and save it immediately.


! To save the R script either use shortcut ( command+S or ctrl+S ) or click
on File > Save or Save As ...

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 18/40
Installing R & RStudio RStudio R Conclusion

Scripts

Three different ways to run your code from a script:


1 One line at a time: Place the cursor on the line you want to run and hit
command+enter / ctrl+enter or use the Run button.

2 Multiple lines: Select the lines you want to run and hit command+enter /
ctrl+enter , or use the Run button.
3 Entire script: Use the Source button.

ctnltF
savefilelcommand 7

clickFile- 7save → .
.
.
.
.
. . . . .
. . . .
. . . .
. . . .
. . . .
. . . . .
.
.
.
.
.
.
.
.
.
19/40
Installing R & RStudio RStudio R Conclusion

Other Windows

Environment/History/Connections ( f: le 仔)
! The "Environment" tab: 7 Save the object
! All the objects (to be discussed later) you have created in the current
(global) environment are displayed here.
! Objects can be displayed as a List ( ) or in Grid ( ) format by
selecting your choice from the drop down button on the top right of the
window.
! In the Grid format, you can remove objects from the environment.
! The "History" tab:
! It contains a list of all the commands you have entered into the R Console.
! You can search back through your history for the line of code you have
forgotten, send selected code back to the Console by double clicking the line.
! We usually never use this as we always refer back to our R script.
! The "Connections" tab:
! It allows you to connect to various data sources such as external databases.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 20/40
Installing R & RStudio RStudio R Conclusion

Other Windows

Files/Plots/Packages/Help/Viewer

! The "Files" tab:


! It lists all external files and directories in the current working directory on
your computer.
! It works like file explorer (Windows) or Finder (Mac). You can open, copy,
rename, move and delete files listed in the window.
! The "Plots" tab:
! All the plots you create in R are displayed here (unless you tell R otherwise).
! : to make the plots large.
! : to scroll back through previously created plots.
! : to export the plots in various file formats (e.g. jpeg, png, pdf, etc.)
! The "Packages" tab:
! Here lists all of the packages that you have installed on your computer.
! You can also install new packages and update existing packages by clicking
on the "Install" ( ) and "Update" buttons ( ) respectively.
! The "Help" tab displays the R help documentation for any function.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 21/40
Installing R & RStudio RStudio R Conclusion

The R Programming Language

! To use R, we need to learn its language


! the R programming language
! R is both the name of the program and the name of the language.

! Learning a programming language is like learning a foreign language.


! not easy
! requires practice
! requires patience

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 22/40
Installing R & RStudio RStudio R Conclusion

We will use R to:

1 Do calculations

2 Create objects Yin fotdafa


-

3 Work with vectors

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 23/40
Installing R & RStudio RStudio R Conclusion

Doing calculations

1. Do calculations

! We can use R as a calculator.


! R understands arithmetic operators such as +, −, ∗, /.
! Operators: symbols that help us to perform specific mathematical and
logical computations on operands.

operation operator example input example output


addition + 10 + 2 12
subtraction − 9−3 6
multiplication * 5*5 25
division / 10 / 3 3
power ˆ 5ˆ2 25

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 24/40
Installing R & RStudio RStudio R Conclusion

Doing calculations

Basic arithmetic operations

! Let’s ask R to calculate 20 plus 5.


1 We type on the R script (upper left window): 20+5
2 To run this code: we highlight it and either
! manually hit the run icon ( ), or
! use the shortcut command+enter in Mac or ctrl+enter in Windows.

5ˆ4
## [1] 625

! R follows the conventional order of operations.


(1 + 2) * 4
## [1] 12

4/2*3
## [1] 6
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 25/40
Installing R & RStudio RStudio R Conclusion

Creating objects

2. Create objects ( <- )

! R stores information in the form of objects.


! In order to analyze data, we will need to create objects.
! An object is like a box that can contain anything.

To create one, we need to:


! give it a name
! specify its contents
! use the assignment operator <-

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 26/40
Installing R & RStudio RStudio R Conclusion

Creating objects

Assignment operator: <-

! To its left, we specify the name of the object.


! To its right, we specify the content of the object.
! Example: create an object which stores the result of a simple addition.
! To create a new object called my_result:

my_result <- 10 + 4

! To see what’s in my_result, just type:

my_result ## [1] 14

This is equivalent of asking to R: what is inside of my_result?

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 27/40
Installing R & RStudio RStudio R Conclusion

Creating objects

Do calculations with objects

! Calculate on an object:
! Both objects appear in the
Environment pane in RStudio.
my_result * 2 ## [1] 28

! Assign the result to a new object:

my_new_result <- my_result * 2


my_new_result ## [1] 28 ! You can use the broom button to
delete all objects.
! In the "Grid" view, you can find a summary of the objects:
! Type: numeric - it’s a number; Length: only one value in the object; Size:
its "physical" size; Value: 14 for my_result, and 28 for my_new_result.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 28/40
Installing R & RStudio RStudio R Conclusion

Creating objects

How to name an object?

A few simple rules to follow when we name objects:


! All object names must start with a letter.
! CANNOT begin with a number.
! Names can contain upper or lower case letters (A-Z, a-z), numbers (0-9),
underscores (_) or a dot (.).
! CANNOT contain spaces or special symbols like $ or % that are reserved for
other purposes.
! Choose names that are descriptive and easy to type.

Good Object Names Bad Object Names


result a
my_result x1
my.result this.name.is.just.too.long
my_new_result thing

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 29/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

3. Vectors
! Vector: a set of information contained together in a specific order.
! Normally numbers, but often also character strings or logical elements.

! To create a vector, use c( ), which "concatenates" or "combines" many


values together.
my_first_vector <- c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
my_first_vector
## [1] 0 1 1 2 3 5 8 13 21 34

! Use c( ) to combine multiple vectors:


of
a <- c( 1, 2, 3 )
b <- c( 4, 5, 6 )
to save a
pund
x <- c( a, b ) humber
x
## [1] 1 2 3 4 5 6
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 30/40
Installing R & RStudio RStudio R Conclusion

check
Working with vectors
() (

Vector indexing: [ ]
弟年但 number 是什麼
! The order in which the numbers in the vector are stored is important.
! Indexing: to access specific elements of a vector.
! To access an individual element of a vector, use square bracket [ ].
my_first_vector
## [1] 0 1 1 2 3 5 8 13 21 34
my_first_vector[ 3 ]
## [1] 1

! To access multiple elements of a vector via another vector within the [ ].

my_first_vector[ c(1,3,4,5) ]
## [1] 0 1 2 3

element
Cun check pant of the
.
.
.
.
.
. . . . .
. . . .
. . . .
. . . .
. . . .
. . . . .
.
.
.
.
.
.
.
.
.
31/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

! Use the colon ":" to extract a range of elements of a vector:


my_first_vector
## [1] 0 1 1 2 3 5 8 13 21 34
my_first_vector[ 3:5 ]
## [1] 1 2 3

! Use the minus sign "– " to remove the corresponding element from a vector:
my_first_vector[ - c(8:10) ]
## [1] 0 1 1 2 3 5 8

! Note: none of these operations change the original vector.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 32/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

Other types of vectors: Character strings


" "

! Character string: something like a word or text -


7 must add
! To create an object that stores the word "hello":

greeting <- "hello"


greeting
## [1] "hello"
! Note: Here, R stores the entire word "hello" as a single element.
greeting[1]
## [1] "hello"
! To create a charactor vector – months:
months <- c ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec")
months[2]
## [1] "Feb"
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 33/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

! What would happen if you run instead: class <- sosc1100?

class <- sosc1100


## Error: object ’sosc1100’ not found

! Without the " ", R thinks that sosc1100 is the name of an object and R is
right; there is no object called sosc1100 in the environment.

! Running into errors is part of the coding process.


! Do not be discouraged.
! If you have problems figuring out what a particular error means, google it;
there are lots of Q&A sites.
! if that doesn’t help, post the code and error in our Canvas’s Discussion
section.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 34/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

When do we need to use " " when writing code in R?


! No need: The names of objects, names of functions, and names of
arguments as well as special values such as TRUE,FALSE, NA, and
NULL should NOT be in quotes.
! Numbers should NEVER be in quotes unless you want R to treat
them as text.
! All other text should be in quotes.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 35/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

! R will overwrite objects if you assign new content to an existing object


name.
class <- "data analysis"

! After running the code above, class will contain the text "data analysis"
instead of "sosc1100"

! R is case sensitive:
! class is different from Class.

Class
## Error: object ’Class’ not found

! To avoid confusion, we use lower-case letters when naming objects.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 36/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

Other types of vectors: logical elements

! A slogan used by the Big Brother : "2 + 2 = 5" (Orwell’s 1984 )


! While humans may adopt the proposition, R is not infinitely malleable.

2 + 2 == 5
## [1] FALSE check the statemeht
! We use the equality operator == to force R to make a "true/false"
judgment.

! When we force R to believe that 2+2=5 by making an assignment


statement:
2+2=5
Error in 2+2=5: target of assignment expands to non-language object

! Remember, "2+2" is not an object’s name.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 37/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

cnly
貪 savenoinenviunmet

What are the differences between 0


= and <-?
! There are different assignment operators: <-, =, and ->.
! -> is almost identical to <-, just that the arrow (i.e., the
assignment) goes from left to right.
! When creating an object, <- and = are identical.
! An example to compare <- and = in a function:
mean( x = 1 : 10 )
x
Error: object ’x’ not found
! Here, x is declared within the scope of the function, so it does not
exist in the user workspace (not in the Environment pane).
mean( x <- 1 : 10 )
x ## [1] 1 2 3 4 5 6 7 8 9 10
! Here, x is declared in the user workspace (see the Environment pane).

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 38/40
Installing R & RStudio RStudio R Conclusion

Working with vectors

! Example of a logical vector:

x <- c( 2, 8, 4, 10, 5, 3, 9)

! To check whether each of the numerical elements is greater than 5:

x>5
## [1] FALSE TRUE FALSE TRUE FALSE FALSE TRUE

sarrtheststeniat
! We can store the output in a vector y:

y <- x>5
y ## [1] 空但的 tiyt

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 39/40
Installing R & RStudio RStudio R Conclusion

Today’s Lecture
! RStudio: R script, R console, and the environment
! How to use R:
1 Do calculations: +, −, ∗, /, ˆ
2 Create objects: <-,
3 Working with vectors: c(), [ ], " ", =, ==

Class Meeting Next Tuesday


! Review what you learned from this lecture
! Practice R in RStudio
! Before coming to the class, install R and RStudio on your computer:
! R: https://cran.r-project.org/
! RStudio: https://posit.co/products/open-source/rstudio/

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 40/40

You might also like