R Basic

NoteIntroduction

Welcome to the Basic R Tutorial webpage! This tutorial will give you an easy to follow and example-led approach to understand the foundation of R. You are welcome and encouraged to modify and test with the code here.

1 Data Types

1.1 Numeric, integer, character/string, and logical

1.1.1 Numeric

Numeric data contain numbers, this also includes decimals.

print(0.1)
[1] 0.1
print(1)
[1] 1

1.1.2 Integer

Integer data are values that do not have decimals.

print(10)
[1] 10
TipNote

An integer is just a subset of numeric data. The integer data type can only be whole numbers, while numeric data can be all kinds of numbers.

1.1.3 Character/String

A string is a sequence of characters that represents text in programming.

print("GWU")
[1] "GWU"

1.1.4 Logical/Boolean

Boolean represents a logical data type that can have one of two possible values: TRUE or FALSE. In R, logical values are used to represent the result of comparisons and conditions.

print(TRUE)
[1] TRUE
print(FALSE)
[1] FALSE

2 Variables

2.1 How can we assign a variable?

Use the <- operator to assign a value to a variable. You can assign any data type to a variable: numeric, integer, character/string, and logical/boolean.

TipTip

You can assign variables using the following operators: <-, =, or ->. THe most common (and in our opinion, easiest) way to assign variables uses the <- operator.

age <- 42
gw_student <- TRUE
firstvariable <- "AppliedEcon"
print(firstvariable)
[1] "AppliedEcon"

2.2 How to determine the type of a variable

Usually we can use these built-in functions: typeof() and class() to determine type of data.

gender <- "female"
typeof(gender)
[1] "character"
class(gender)
[1] "character"

2.3 Rules for assigning variables in R:

  • Variable names can contain letters, numbers, dots, and underscores.
  • Variable names must start with a letter or a dot not followed by a number.
  • Variable names are case sensitive (e.g., myVar and myvar are different).
  • Avoid using reserved words (like if, else, TRUE, FALSE, etc.).

Examples of valid variable names:

num_students <- 10
class2 <- 20
.var <- 30

Examples of invalid variable names:

2var <- 40
_var <- 50
if <- 60
Error in parse(text = input): <text>:1:2: unexpected symbol
1: 2var
     ^

3 Data Structures

3.1 Vectors, lists, matrices, arrays, and data frames

3.1.1 Vectors

Vectors can only contain variables that have the same data type. We call this homogenous data.

x <- c(1,2,3,4,5,6,7)
y <-c("a", "b", "c", "d", "e","f","g","h")
cat("the first 6 item in x are:", head(x), ", the last 6 item in y are:" , tail(y) , "\n")
the first 6 item in x are: 1 2 3 4 5 6 , the last 6 item in y are: c d e f g h 

3.1.2 Lists

A list is a collection of ordered data. It can contain different data types inside it (heterogenous data). Lists can be used for vectors, matrices, list of characters, and list of functions.

classrank = c(1, 2, 3, 4)
studentName = c("Constantine", "Laura", "Ha", "Snoopy")
numberofstudent = 4
classList = list(classrank, studentName, numberofstudent)
classList
[[1]]
[1] 1 2 3 4

[[2]]
[1] "Constantine" "Laura"       "Ha"          "Snoopy"     

[[3]]
[1] 4
classList2 = list(classList, c(5, 6, 7, 8), "We are all students at GWU")
print(classList2)
[[1]]
[[1]][[1]]
[1] 1 2 3 4

[[1]][[2]]
[1] "Constantine" "Laura"       "Ha"          "Snoopy"     

[[1]][[3]]
[1] 4


[[2]]
[1] 5 6 7 8

[[3]]
[1] "We are all students at GWU"

3.1.3 Matrices

A matrix is a two-dimensional data set with columns and rows.

matrix_X <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)
matrix_Y <- matrix(c("odd","even",1,2,3,4,5,6) , nrow = 2 , ncol = 4)
matrix_X
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
matrix_Y
     [,1]   [,2] [,3] [,4]
[1,] "odd"  "1"  "3"  "5" 
[2,] "even" "2"  "4"  "6" 

3.1.4 Array

An array is a collection of data. The data must all be the same type (homogenous data), have a fixed size, and can be multidimensional.

peanuts_characters <- c("Snoopy", "Linus", "Lucy", "Charlie", "Woodstock", "Sally")
peanutsarray <- array(peanuts_characters)
peanutsarray
[1] "Snoopy"    "Linus"     "Lucy"      "Charlie"   "Woodstock" "Sally"    
testscores <- c(60, 96, 73, 86, 90, 91, 89, 82, 65, 77, 80, 50)
scoresarray <- array(testscores, dim = c(2,3,2))
print(scoresarray)
, , 1

     [,1] [,2] [,3]
[1,]   60   73   90
[2,]   96   86   91

, , 2

     [,1] [,2] [,3]
[1,]   89   65   80
[2,]   82   77   50

3.2 Data Frame

A data frame is like spreadsheet. It can hold different types of data and have multiple columns and rows.

Dataframe_Testing_Scores <- data.frame(
    Names = c("Abby", "Bob", "Chris", "Denny"),
    Score =c(90, 87, 67, 91),
    Pass_Class = c(TRUE, TRUE, FALSE, TRUE)
)
Dataframe_Testing_Scores
  Names Score Pass_Class
1  Abby    90       TRUE
2   Bob    87       TRUE
3 Chris    67      FALSE
4 Denny    91       TRUE
TipWhich types of data can go where again?
Data Structure Data Types Allowed
Vector Only one data type (homogenous)
List Multiple data types (heterogenous)
Matrix Only one data type (homogenous)
Array Only one data type (homogenous)
Data Frame Multiple data types (heterogenous)

4 Additional Note: How to “comment out”

Simply insert a # sign and then write your comment for your code to enhance its reproducability and clarity. You can also comment out pieces of code to test various methods of completing a task.

#You can write a comment exactly like this. Notice the color?

print("4times")
[1] "4times"

5 Video tutorial and other resources

Video Tutorial for basic coding in R studio

Online book for Learning R

6 Interview Questions / Quiz Yourself!

NoteNote

On this page, you will find some interview questions to practice your basic knowledge of R programming. All of the content is based on the R Basic tutorial from this page.

Even if you are not preparing for an interview, these questions can help test your knowledge (perhaps for an upcoming exam, certification, or homework assignment!).

TipTip

Try to actively recall the answers before checking them. This is one of the most effective ways to learn and increase retention!

6.1 Quiz Questions (without answers)

Download Basic R Quiz

NoteQuestion 1: What is the main difference between a vector and a list in R?

A. A vector can contain elements of different types, a list cannot.
B. A vector contains elements of the same type, while a list can contain elements of different types.
C. Both vectors and lists can only contain numeric values.
D. There is no difference; they are the same in R.

B. A vector contains elements of the same type, while a list can contain elements of different types.

NoteQuestion 2: What data type is this?

12months

A. Numeric
B. Boolean
C. Character
D. Integer

C. Character

NoteQuestion 3: What operator is correctly used to assign a variable?

A. <-
B. //
C. :
D. ( )

A. <-

NoteQuestion 4: Why will this code not run?

daysof.week <- c(“Monday1”, “Tuesday”, “Wednesday”, “Thursday”, “Friday” “Saturday”, “Sunday”, 7)

A. The variable name is invalid.
B. There is a missing comma.
C. Arrays need different data types, not the same data types.
D. The array( ) function cannot be used with character data.

B. There is a missing comma.
- Bonus Tip: R doesn’t care that “Monday1” includes a number — it still treats the entire value as a character string. It also “coerces” the 7 to a character string in the vector becaue it must be the

NoteQuestion 5: What is the data type in this array?
daysof.week <- c("Monday1", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", 7)
daysof.week <- array(daysof.week)

A. Numeric
B. Logical
C. Integer
D. Character

D. Character.
- Bonus Tip: Mixing “Monday1” (a character string) and 7 (a number) in a vector causes R to coerce all elements to character.

Back to top