Intermediate R

Harold Nelson

2025-09-08

Exercise

The following command produces a list.

lst1 = list(x = c(1,3), y = c("a","b"))
lst1
## $x
## [1] 1 3
## 
## $y
## [1] "a" "b"

Write R code which extracts the value “a” and stores it in a variable my_value.

Solution

my_value = lst1[[2]][1]
my_value
## [1] "a"

Or, we could use the following.

my_value = lst1$y[1]
my_value
## [1] "a"

Exercise

What is the difference between [[]] and [] when extracting from a list?

Solution

two_brackets = lst1[[2]]
str(two_brackets)
##  chr [1:2] "a" "b"
one_bracket = lst1[2]
str(one_bracket)
## List of 1
##  $ y: chr [1:2] "a" "b"

Exercise

Compare one bracket and two brackets for a dataframe. Use the builtin datafram mtcars.

Solution

one_bracket = mtcars[1]
str(one_bracket)
## 'data.frame':    32 obs. of  1 variable:
##  $ mpg: num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
two_brackets = mtcars[[1]]
str(two_brackets)
##  num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...

A Traditional Basic Algorithm

Write code to calculate the number of 7’s in a numeric vector.

Solution

the_vector = c(1,2,7,4,7)

count = 0

for(i in the_vector){
  if(i == 7){
    count = count + 1
  }
}

count
## [1] 2

Act Like an R Programmer

Solution

sum(the_vector == 7)
## [1] 2

Why does it work

bool = the_vector == 7
bool
## [1] FALSE FALSE  TRUE FALSE  TRUE
sum(bool)
## [1] 2

The Proportion of 7’s

Solution

mean(the_vector == 7)
## [1] 0.4

The mean of a logical expression is the fraction of cases for which the logical expression is true.

The sum of a logical expression is the count of cases for which the logical expression is true.