WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

R · Basic · question 14 of 100

How do you subset data in R using square brackets []?

📕 Buy this interview preparation book: 100 R questions & answers — PDF + EPUB for $5

In R, you can subset data using square brackets []. Subsetting is the process of selecting a subset of rows, columns, or elements from a data frame, matrix, or vector. The square brackets can be used to specify one or more indices, which indicate the subset of data to be selected.

Here are some examples of subsetting data using square brackets:

Subsetting a vector:

    # Creating a vector
    x <- c(1, 2, 3, 4, 5)
    
    # Selecting the second element of the vector
    x[2]
    # Returns 2
    
    # Selecting the first three elements of the vector
    x[1:3]
    # Returns c(1, 2, 3)

In this example, we create a vector x and use square brackets to select the second element of the vector (x[2]) and the first three elements of the vector (x[1:3]).

Subsetting a matrix:

    # Creating a matrix
    m <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
    
    # Selecting the element in the second row and third column
    m[2, 3]
    # Returns 6
    
    # Selecting the first row of the matrix
    m[1, ]
    # Returns c(1, 3, 5)

In this example, we create a matrix m and use square brackets to select the element in the second row and third column (m[2, 3]) and the first row of the matrix (m[1, ]).

Subsetting a data frame:

    # Creating a data frame
    df <- data.frame(x = c(1, 2, 3), y = c(4, 5, 6))
    
    # Selecting the value in the first row and second column of the data frame
    df[1, 2]
    # Returns 4
    
    # Selecting the second column of the data frame
    df[, 2]
    # Returns c(4, 5, 6)
    
    # Selecting rows where the value of x is greater than 1
    df[df$x > 1, ]
    # Returns a data frame with rows 2 and 3

In this example, we create a data frame df and use square brackets to select the value in the first row and second column of the data frame (df[1, 2]), the second column of the data frame (df[, 2]), and the rows where the value of x is greater than 1 (df[df$x > 1, ]).

In summary, subsetting data in R using square brackets [] is a powerful and flexible way to select subsets of rows, columns, or elements from a data frame, matrix, or vector.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic R interview — then scores it.
📞 Practice R — free 15 min
📕 Buy this interview preparation book: 100 R questions & answers — PDF + EPUB for $5

All 100 R questions · All topics