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

R · Intermediate · question 25 of 100

What is the difference between deep and shallow copies of objects in R? How do you create each type of copy?

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

In R, copying an object creates a new object with the same values as the original object. However, there are two types of copies in R: deep copies and shallow copies.

A shallow copy (also called a "reference copy") creates a new object that points to the same memory location as the original object. This means that any changes made to the new object will also affect the original object. Shallow copies are created using the assignment operator (<-) or the = operator.

Here’s an example of creating a shallow copy in R:

    # Create a vector
    x <- c(1, 2, 3)
    
    # Create a shallow copy of the vector
    y <- x
    
    # Change a value in the new vector
    y[1] <- 10
    
    # Print both vectors
    print(x)
    print(y)

In this example, we create a vector x with three elements, and then create a shallow copy of x called y. We then change the first element of y to 10, and print both x and y. Since y is a shallow copy of x, the change to y also affects x, and both vectors will contain the value 10 in the first position.

A deep copy creates a new object with the same values as the original object, but in a separate memory location. This means that changes made to the new object will not affect the original object. Deep copies can be created using functions such as clone(), copy(), and dput().

Here’s an example of creating a deep copy in R:

    # Create a vector
    x <- c(1, 2, 3)
    
    # Create a deep copy of the vector
    y <- clone(x)
    
    # Change a value in the new vector
    y[1] <- 10
    
    # Print both vectors
    print(x)
    print(y)

In this example, we create a vector x with three elements, and then create a deep copy of x called y using the clone() function. We then change the first element of y to 10, and print both x and y. Since y is a deep copy of x, the change to y does not affect x, and the vectors will have different values.

In summary, the difference between deep and shallow copies in R is that a shallow copy creates a new object that points to the same memory location as the original object, while a deep copy creates a new object in a separate memory location. Shallow copies are created using the assignment operator or the = operator, while deep copies are created using functions such as clone(), copy(), and dput().

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