R Intermediate

NoteIntroduction

Welcome to the Intermediate R Tutorial webpage! This tutorial will cover more complex topics within R like indexing and slicing, logical operators, and an example user-defined function cover loop and if-else logical statement.

1 Indexing and Slicing

1.1 Indexing in One-Dimensional Data Structure (example: vector).

1.1.1 Access a single element in the vector.

The basic syntax for accessing an element is object[index].

TipNote

Indexing in R starts at 1 instead of 0.

GWU_Rating <- c(100, 98, 76, 61, 88, 90, 76, 83)
GWU_Rating[1]
[1] 100
GWU_Rating[4]
[1] 61

1.1.2 Exclude an element in the vector.

The syntax for excluding an element is object[-index].

GWU_Rating[-3]
[1] 100  98  61  88  90  76  83

1.1.3 Access multiple elements in the vector.

The syntax for accessing X and Y element is object[c(X,Y)].

The syntax for accessing from the Xth element to the Yth element is object[x:y].

GWU_Rating[c(1, 4)]
[1] 100  61
GWU_Rating[1:6]
[1] 100  98  76  61  88  90

1.1.4 Logical indexing

The syntax for logical indexing is object[logical statement].

GWU_Rating[GWU_Rating >75]
[1] 100  98  76  88  90  76  83

1.2 Indexing and slicing in Multi-Dimensional Data Structure (example: dataframe)

1.2.1 Indexing a certain column.

You can either directly access by using the name of a column or by the number of columns.

TipNote

The number goes from left to right for columns, so the left-most column is column 1.

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
Dataframe_Testing_Scores["Score"]
  Score
1    90
2    87
3    67
4    91
Dataframe_Testing_Scores[2:3]
  Score Pass_Class
1    90       TRUE
2    87       TRUE
3    67      FALSE
4    91       TRUE

1.2.2 Slicing with [ , ].

The syntax is [row number , column number] For example, here we are fetching the first row and the first two columns in this dataframe.

Dataframe_Testing_Scores[1,c(1,2)]
  Names Score
1  Abby    90

1.2.3 Slicing with subset() function.

Subset() is a built-in function in base R. You need to provide the input dataframe and parameters to indicate which part of the dataframe you want to keep. Here is an example for selecting the columns Names and Score.

Testing_Score_New <- subset(Dataframe_Testing_Scores, select = c(Names, Score) )
Testing_Score_New
  Names Score
1  Abby    90
2   Bob    87
3 Chris    67
4 Denny    91

1.2.4 Subset() function with logical statement

Here is another example for using a logical statement to only select students that passed the class.

Testing_Score_Pass <- subset(Dataframe_Testing_Scores, Pass_Class == TRUE )
Testing_Score_Pass
  Names Score Pass_Class
1  Abby    90       TRUE
2   Bob    87       TRUE
4 Denny    91       TRUE

2 Logical Operators in R

x <- TRUE
y <- FALSE
a <- 2
b <- 2
c <- 3

2.1 Equal operator ==

The equal operator returns TRUE when both elements are equal to each other, otherwise it returns FALSE.

cat( "x is:", x , " and y is:" , y , " Is x equal to y?  Answer:", x == y)
x is: TRUE  and y is: FALSE  Is x equal to y?  Answer: FALSE

2.2 Not equal operator !=

The not equal operator returns FALSE when both elements are equal to each other, otherwise it returns TRUE.

cat( "x is:", x , " and y is:" , y , " Is x not equal to y? Answer:", x!= y)
x is: TRUE  and y is: FALSE  Is x not equal to y? Answer: TRUE

2.3 Greater than operator >

The greater than operator returns TRUE when the first element is greater than the second element, otherwise it returns FALSE.

cat("a is:", a , " and c is:" , c , " Is a greater than c? Answer:", a > c)
a is: 2  and c is: 3  Is a greater than c? Answer: FALSE

2.4 Smaller than operator <

The smaller than operator returns TRUE when the first element is smaller than the second element, otherwise it returns FALSE.

cat("a is:", a , " and c is:" , c , " Is a smaller than c? Answer:" , a < c)
a is: 2  and c is: 3  Is a smaller than c? Answer: TRUE

2.5 Greater than or equal to operator >=

The greater than operator returns TRUE when the first element is greater than or equal to the second element, otherwise it returns FALSE.

cat("a is:", a , " and b is:" , b , " Is a greater than or equal to b? Answer:" , a >= b)
a is: 2  and b is: 2  Is a greater than or equal to b? Answer: TRUE

2.6 Smaller than or equal to operator <=

The smaller than operator returns TRUE when the first element is smaller than or equal to the second element, otherwise it returns FALSE.

cat("a is:", a , " and c is:" , c , " Is a smaller than or equal to c? Answer:" , a <= c)
a is: 2  and c is: 3  Is a smaller than or equal to c? Answer: TRUE

2.7 And operator &&

The and operator only returns TRUE when both elements are true, otherwise it returns FALSE. In this case, x is true and y is false, so the and operator would return:

print(x && y)
[1] FALSE

2.8 Or operator ||

The or operator only returns FALSE when both elements are false, otherwise it returns FALSE. In this case, x is true and y is false, so the or operator would return:

print(x || y)
[1] TRUE

3 Example Function

This function includes a for loop and if-else statement. It loops through a vector and calculates the percentage of students that passed the test.

pass_percentage <- function(scores, passing_score = 70) {
  pass_count <- 0
  fail_count <- 0

  for(score in scores) {
    if(score >= passing_score) {
      pass_count <- pass_count + 1
    } else {
      fail_count <- fail_count + 1
    }
  }
  pass_percent <- (pass_count / length(scores)) * 100
  cat("Students who passed the class:", pass_percent, "%\n")
  return(list(pass_count = pass_count, fail_count = fail_count, pass_percent = pass_percent))
}
class_scores <- c(60,70,72,89,91,79,90,95,84,87,76,93,73,74,50,85,78,80,95,79,69,77,69,66,81)
pass_percentage(class_scores)
Students who passed the class: 80 %
$pass_count
[1] 20

$fail_count
[1] 5

$pass_percent
[1] 80

4 Interview Questions / Quiz Yourself!

NoteNote

On this page, you will find some interview questions to practice your intermediate knowledge of R programming. All of the content is based on the R Intermediate 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!

4.1 Quiz Questions (without answers)

Download Intermediate R Quiz

NoteQuestion 1: Which of the following is the correct syntax to access the “sales” column from a data frame in R called annual.revenue?

A. annual.revenue[“sales”]
B. annual.revenue$sales
C. annual.revenue.sales
D. annual.revenue[sales]

B. annual.revenue$sales

NoteQuestion 2: After running the code below, what is the class of the column age?
aot <- data.frame(
  name = c("Eren", "Levi"),
  age = c(19, 38))
class(aot$age)
[1] "numeric"

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

C. Numeric

NoteQuestion 3: What is the output?
age <- c(5, 10, 15, 20, 25, 30, 35, 40)
age[age <= 24]
[1]  5 10 15 20

A. 5, 10, 15, 20
B. 25, 30, 35, 40
C. 15, 20
D. 5, 10, 15, 20, 24

A. 5, 10, 15, 20

NoteQuestion 4: What data type(s) will the parameter x take in this function? Select all that apply.
monthlyrevenue <- function(x) {
  fixed_costs <- 500
  net_profit <- x - fixed_costs

  if (net_profit <= 500) {
    return("In the red")
  } else {
    return("In the green")
  }
}

A. Numeric
B. Integer
C. NULL – the code won’t run due to a syntax error.
D. Character

A. Numeric, B. Integer

NoteQuestion 5: What will this slice return?
countries <- data.frame(
  country = c("USA", "Canada", "France"),
  foundingyear = c(1776, 1867, 1792),
  population_million = c(340.1, 40.1, 68.29)
)
countries[1:2, ]

A. The entire data frame with all three countries.
B. Only the first two columns of the data frame.
C. A syntax error because of incorrect indexing.
D. The first two rows of the data frame, showing all columns.

D. The first two rows of the data frame, showing all columns.

  country foundingyear population_million
1     USA         1776              340.1
2  Canada         1867               40.1
Back to top