← Back to quizzesFree quiz

Fundamentals of R Programming

Welcome to this comprehensive module on the core concepts of R programming. Whether you are a beginner or looking to solidify your foundation, this course will walk you through essential…

16 questions~8 min
Fundamentals of R Programming — Qwi
0 / 16
Score: 0%
1

Which operator correctly assigns a vector to a variable without creating a duplicate object?

2

What will be the result of evaluating the expression `9 %/% 2` in R?

3

Given `y <- c(1,9,9,9)`, what does the command `y[y<9] = 2` achieve?

4

Which function creates a factor variable from a character vector and automatically determines its levels?

5

When constructing a data frame, why might one set `stringsAsFactors = FALSE`?

6

What does the expression `dim(x) > 9` return when `x` is a 3x3 array?

7

Which of the following statements about the `c()` function is FALSE?

8

If `z <- list(batch=3,label="Lung Cancer Patients",subtype=c("A","B","C"))`, how would you extract the vector of subtypes?

9

What is the purpose of the `na.rm=TRUE` argument in functions like `mean()`?

10

Which command correctly displays the first three rows of a data frame `df`?

11

When using `table(A,B)` to create a contingency table, what does `margin.table(tab, 1)` return?

12

What is the effect of executing `rm(x)` in the R console when `x` exists?

13

Which of the following best describes the difference between a matrix and a data frame in R?

14

What does the function `str()` display when applied to a data frame?

15

If you need to import a comma‑separated file with a header row, which function and arguments are most appropriate?

16

Which of the following statements about the `%%` operator is true?

Fundamentals of R Programming

Welcome to this comprehensive module on the core concepts of R programming. Whether you are a beginner or looking to solidify your foundation, this course will walk you through essential topics such as assignment operators, vector indexing, factor creation, data‑frame handling, and more. Each section is designed to be SEO‑friendly, using clear headings, concise paragraphs, and keyword‑rich lists to help both learners and search engines understand the material.

1. Assignment Operators in R

R provides several ways to assign values to objects, but the most idiomatic and efficient operator is the left‑arrow <-. Unlike the equals sign (=) which can create a duplicate copy in certain contexts, <- assigns a vector directly to a variable without unnecessary duplication.

  • Correct usage: x <- c(1, 2, 3)
  • Alternative forms such as x = c(1,2,3) work in simple scripts but may lead to ambiguous scoping in functions.
  • The super‑assignment operator <<- modifies variables in parent environments and should be used sparingly.
  • The assign() function is useful for programmatic variable creation but is less readable than <-.

Understanding the nuances of assignment helps you write cleaner, faster code and avoid common pitfalls related to object copying.

2. Modulo Operator (%/%) – Integer Division

R’s integer division operator %/% returns the whole‑number quotient of a division, discarding any remainder. For example, evaluating 9 %/% 2 yields 4 because 2 fits into 9 four times with a remainder of 1.

  • Use %% for the remainder (modulus) operation.
  • Combine %/% and %% to perform floor division and retrieve both quotient and remainder.
  • These operators are vectorized, meaning they work element‑wise on vectors.

3. Vector Indexing and Conditional Replacement

R allows you to modify specific elements of a vector using logical conditions. Consider the vector y <- c(1, 9, 9, 9). The command y[y < 9] <- 2 replaces every element that is less than 9 with the value 2. After execution, y becomes c(2, 9, 9, 9).

  • Logical indexing is a powerful tool for data cleaning and transformation.
  • Multiple conditions can be combined using & (and) or | (or).
  • Remember that the original vector is modified in place when using the assignment operator.

4. Creating Factor Variables

Factors are R’s way of handling categorical data. The function factor() converts a character vector into a factor and automatically determines the levels based on the unique values present.

colors <- c("red", "blue", "red", "green")
color_factor <- factor(colors)

In this example, color_factor will have levels "blue", "green", and "red". Using as.factor() achieves the same result, but factor() is the canonical, more readable form.

5. Controlling String Conversion in Data Frames

When constructing a data frame, R historically converted character columns to factors by default. Setting stringsAsFactors = FALSE preserves character columns as plain strings. This is crucial when you need to retain the original text for operations such as string matching, regular expressions, or when the categorical nature of the data is not yet defined.

df <- data.frame(name = c("Alice", "Bob"), stringsAsFactors = FALSE)

Without the argument, name would become a factor, potentially leading to unexpected behavior in downstream analyses.

6. Comparing Dimensions with Scalars

The dim() function returns a numeric vector representing the dimensions of an array or matrix. When you compare dim(x) > 9 for a 3×3 matrix x, the result is a logical vector c(FALSE, FALSE) because each dimension (3) is not greater than 9. Since the comparison yields a vector, R does not coerce it to a single logical value; instead, it returns the element‑wise result.

  • To test whether the total number of elements exceeds a threshold, use length(x) > 9 or prod(dim(x)) > 9.
  • Understanding vectorized logical operations prevents errors when writing conditionals.

7. The c() Function – Common Misconceptions

The combine function c() is the workhorse for creating vectors. It can concatenate elements of different types, coercing them to a common type (e.g., numeric to character). It also works with the colon operator (:) to generate sequences, such as c(1:5). However, c() never creates a list when given named arguments; it still returns a simple atomic vector. To create a list, you must use the list() function.

# Correct list creation
my_list <- list(name = "John", age = 30)

Remembering this distinction helps you avoid unexpected data structures in your scripts.

8. Extracting Elements from Lists

Lists are flexible containers that can hold objects of different classes. To retrieve a specific component, you can use the $ operator or double‑bracket indexing. Given the list:

z <- list(batch = 3,
          label = "Lung Cancer Patients",
          subtype = c("A", "B", "C"))

The vector of subtypes is accessed with z$subtype. While z[["subtype"]] also works, the $ syntax is more concise and idiomatic for named elements.

  • Use z[[1]] to access the first element by position.
  • Use z["subtype"] to obtain a sub‑list containing the element.
  • Understanding these extraction methods is vital for data manipulation and function writing.

9. Summary of Key Takeaways

By mastering the concepts covered in this module, you will be able to write more efficient R code and avoid common mistakes:

  • Assignment: Prefer <- for clear, non‑duplicating assignments.
  • Integer division: Use %/% to obtain whole‑number quotients.
  • Conditional indexing: Leverage logical vectors to modify subsets of data.
  • Factors: Convert character data with factor() and control factor creation with stringsAsFactors = FALSE.
  • Dimension comparison: Remember that dim() returns a vector; use length() for total element counts.
  • Combine function: c() concatenates vectors but never creates lists.
  • List extraction: Use $ or [[ ]] for named components.

These fundamentals form the backbone of effective R programming. Continue practicing by creating your own scripts, experimenting with the functions discussed, and exploring how they integrate within larger data‑analysis workflows.