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 3 of 100

Explain the difference between a vector and a list in R.?

πŸ“• Buy this interview preparation book: 100 R questions & answers β€” PDF + EPUB for $5

In R, a vector is an ordered collection of elements of the same data type, while a list is an ordered collection of elements that can be of different data types.

Vectors in R can be created using the c() function, which combines values into a single vector. For example:

    # Creating a numeric vector
    x <- c(1, 2, 3, 4, 5)
    
    # Creating a character vector
    y <- c("a", "b", "c")

Vectors can also be created using functions like seq() or rep(), which generate sequences or repeated values, respectively.

Lists in R are created using the list() function, which takes any number of arguments and combines them into a list. The elements of a list can be of different data types, and can even be other lists. For example:

    # Creating a list with numeric and character elements
    my_list <- list(1, "a", 3.14)
    
    # Creating a list with a nested list
    nested_list <- list("a", "b", list("x", "y"))

To access elements of a vector, you can use indexing with square brackets. For example, to get the third element of the vector x, you would write x[3].

To access elements of a list, you can also use indexing with square brackets. However, since lists can contain elements of different types, you may need to use the $ operator to access named elements or the [[ ]] operator to access unnamed elements. For example, to get the second element of my_list, which is a character string, you would write my_list[[2]]. To get the first element of nested_list, which is itself a list, you would write nested_list[[1]].

In summary, the main difference between a vector and a list in R is that vectors contain elements of the same data type, while lists can contain elements of different data types, including other lists. Vectors are indexed with square brackets, while lists may require the $ or [[ ]] operators to access specific elements.

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