All topics

R interview questions

9 questions with answers. 232 open jobs in India ask for R.

  1. What are the differences between "=" and "<-" assignment operators?

    The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

    median(x = 1:10)
    x   
    ## Error: object 'x' not found
    

    In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

    median(x <- 1:10)
    x    
    ## [1]  1  2  3  4  5  6  7  8  9 10
    

    In this case, x is declared in the user workspace, so you can use it after the function call has been completed.

    There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

    x<-3
    # Does this mean assignment?
    x <- 3
    # Or less than?
    x < -3
    

    Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.

    If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

    library(formatR)
    tidy_source(text = "x=1:5", arrow = TRUE)
    ## x <- 1:5
    

    The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

    To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

    Secondly, it's clearer if we use prefix notation for assignment. So

    x <- 5
    `<-`(x, 5)  #same thing
    y = 5
    `=`(y, 5)   #also the same thing
    

    The parser interprets x <- y <- 5 as

    `<-`(x, `<-`(y, 5))
    

    We might expect that x <- y = 5 would then be

    `<-`(x, `=`(y, 5))
    

    but actually it gets interpreted as

    `=`(`<-`(x, y), 5)
    

    This is because = is lower precedence than <-, as shown on the ?Syntax help page.

    From Stack Overflow: asked by csgillespie, answered by Richie Cotton (CC BY-SA 3.0)

  2. The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

    The R Language Definition is handy for answering these types of questions:

    R has three basic indexing operators, with syntax displayed by the following examples

        x[i]
        x[i, j]
        x[[i]]
        x[[i, j]]
        x$a
        x$"a"
    

    For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x.

    For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

    The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

    From Stack Overflow: asked by Sharpie, answered by ars (CC BY-SA 4.0)

  3. What is the difference between require() and library()?

    There's not much of one in everyday work.

    However, according to the documentation for both functions (accessed by putting a ? before the function name and hitting enter), require is used inside functions, as it outputs a warning and continues if the package is not found, whereas library will throw an error.

    From Stack Overflow: asked by Marco, answered by richiemorrisroe (CC BY-SA 3.0)

  4. Why is `[` better than `subset`?

    This question was answered in well in the comments by @James, pointing to an excellent explanation by Hadley Wickham of the dangers of subset (and functions like it) [here]. Go read it!

    It's a somewhat long read, so it may be helpful to record here the example that Hadley uses that most directly addresses the question of "what can go wrong?":

    Hadley suggests the following example: suppose we want to subset and then reorder a data frame using the following functions:

    scramble <- function(x) x[sample(nrow(x)), ]
    subscramble <- function(x, condition) {
      scramble(subset(x, condition))
    }
    subscramble(mtcars, cyl == 4)
    

    This returns the error:

    Error in eval(expr, envir, enclos) : object 'cyl' not found

    because R no longer "knows" where to find the object called 'cyl'. He also points out the truly bizarre stuff that can happen if by chance there is an object called 'cyl' in the global environment:

    cyl <- 4
    subscramble(mtcars, cyl == 4)
    cyl <- sample(10, 100, rep = T)
    subscramble(mtcars, cyl == 4)
    

    (Run them and see for yourself, it's pretty crazy.)

    From Stack Overflow: asked by flodel, answered by joran (CC BY-SA 3.0)

  5. Is there an R function for finding the index of an element in a vector?

    The function match works on vectors:

    x <- sample(1:10)
    x
    # [1]  4  5  9  3  8  1  6 10  7  2
    match(c(4,8),x)
    # [1] 1 5
    

    match only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.

    For multiple matching, %in% is the way to go:

    x <- sample(1:4,10,replace=TRUE)
    x
    # [1] 3 4 3 3 2 3 1 1 2 2
    which(x %in% c(2,4))
    # [1]  2  5  9 10
    

    %in% returns a logical vector as long as the first argument, with a TRUE if that value can be found in the second argument and a FALSE otherwise.

    From Stack Overflow: asked by Ryan C. Thompson, answered by Joris Meys (CC BY-SA 4.0)

  6. How to make a great R reproducible example?

    Basically, a minimal reproducible example (MRE) should enable others to exactly reproduce your issue on their machines.

    Please do not post images of your data, code, or console output!

    Brief summary

    A MRE consists of the following items:

    • a minimal dataset, necessary to demonstrate the problem
    • the minimal runnable code necessary to reproduce the issue, which can be run on the given dataset
    • all necessary information on the used librarys, the R version, and the OS it is run on, perhaps a sessionInfo()
    • in the case of random processes, a seed (set by set.seed()) to enable others to replicate exactly the same results as you have

    For examples of good MREs, see section "Examples" at the bottom of help pages on the function you are using. Simply type e.g. help(mean), or short ?mean into your R console.

    Providing a minimal dataset

    Usually, sharing huge data sets is not necessary and may rather discourage others from reading your question. Therefore, it is better to use built-in datasets or create a small "toy" example that resembles your original data, which is actually what is meant by minimal. If for some reason you really need to share your original data, you should use a method, such as dput(), that allows others to get an exact copy of your data.

    Built-in datasets

    You can use one of the built-in datasets. A comprehensive list of built-in datasets can be seen with data(). There is a short description of every data set, and more information can be obtained, e.g. with ?iris, for the 'iris' data set that comes with R. Installed packages might contain additional datasets.

    Creating example data sets

    Preliminary note: Sometimes you may need special formats (i.e. classes), such as factors, dates, or time series. For these, make use of functions like: as.factor, as.Date, as.xts, ... Example:

    d <- as.Date("2020-12-30")
    

    where

    class(d)
    # [1] "Date"
    

    Vectors

    x <- rnorm(10)  ## random vector normal distributed
    x <- runif(10)  ## random vector uniformly distributed    
    x <- sample(1:100, 10)  ## 10 random draws out of 1, 2, ..., 100    
    x <- sample(LETTERS, 10)  ## 10 random draws out of built-in latin alphabet
    

    Matrices

    m <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4]))
    m
    #   A B C  D
    # A 1 4 7 10
    # B 2 5 8 11
    # C 3 6 9 12
    

    Data frames

    set.seed(42)  ## for sake of reproducibility
    n <- 6
    dat <- data.frame(id=1:n, 
                      date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
                      group=rep(LETTERS[1:2], n/2),
                      age=sample(18:30, n, replace=TRUE),
                      type=factor(paste("type", 1:n)),
                      x=rnorm(n))
    dat
    #   id       date group age   type         x
    # 1  1 2020-12-26     A  27 type 1 0.0356312
    # 2  2 2020-12-27     B  19 type 2 1.3149588
    # 3  3 2020-12-28     A  20 type 3 0.9781675
    # 4  4 2020-12-29     B  26 type 4 0.8817912
    # 5  5 2020-12-30     A  26 type 5 0.4822047
    # 6  6 2020-12-31     B  28 type 6 0.9657529
    

    Note: Although it is widely used, better to not name your data frame df, because df() is an R function for the density (i.e. height of the curve at point x) of the F distribution and you might get a clash with it.

    Copying original data

    If you have a specific reason, or data that would be too difficult to construct an example from, you could provide a small subset of your original data, best by using dput.

    Why use dput()?

    dput throws all information needed to exactly reproduce your data on your console. You may simply copy the output and paste it into your question.

    Read the rest at the sourceFrom Stack Overflow: asked by Andrie, answered by Joris Meys (CC BY-SA 4.0)

  7. How to join (merge) data frames (inner, outer, left, right)

    By using the merge function and its optional parameters:

    Inner join: merge(df1, df2) will work for these examples because R automatically joins the frames by common variable names, but you would most likely want to specify merge(df1, df2, by = "CustomerId") to make sure that you were matching on only the fields you desired. You can also use the by.x and by.y parameters if the matching variables have different names in the different data frames.

    Outer join: merge(x = df1, y = df2, by = "CustomerId", all = TRUE)

    Left outer: merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)

    Right outer: merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)

    Cross join: merge(x = df1, y = df2, by = NULL)

    Just as with the inner join, you would probably want to explicitly pass "CustomerId" to R as the matching variable. I think it's almost always best to explicitly state the identifiers on which you want to merge; it's safer if the input data.frames change unexpectedly and easier to read later on.

    You can merge on multiple columns by giving by a vector, e.g., by = c("CustomerId", "OrderId").

    If the column names to merge on are not the same, you can specify, e.g., by.x = "CustomerId_in_df1", by.y = "CustomerId_in_df2" where CustomerId_in_df1 is the name of the column in the first data frame and CustomerId_in_df2 is the name of the column in the second data frame. (These can also be vectors if you need to merge on multiple columns.)

    From Stack Overflow: asked by Dan Goldstein, answered by Matt Parker (CC BY-SA 4.0)

  8. Sort (order) data frame rows by multiple columns

    You can use the order() function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:

    R> dd[with(dd, order(-z, b)), ]
        b x y z
    4 Low C 9 2
    2 Med D 3 1
    1  Hi A 8 1
    3  Hi A 9 1
    

    Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order() function:

    R> dd[order(-dd[,4], dd[,1]), ]
        b x y z
    4 Low C 9 2
    2 Med D 3 1
    1  Hi A 8 1
    3  Hi A 9 1
    R> 
    

    rather than using the name of the column (and with() for easier/more direct access).

    From Stack Overflow: asked by Christopher DuBois, answered by Dirk is no longer here (CC BY-SA 4.0)

  9. Grouping functions (tapply, by, aggregate) and the *apply family

    R has many *apply functions which are ably described in the help files (e.g. ?apply). There are enough of them, though, that beginning useRs may have difficulty deciding which one is appropriate for their situation or even remembering them all. They may have a general sense that "I should be using an *apply function here", but it can be tough to keep them all straight at first.

    Despite the fact (noted in other answers) that much of the functionality of the *apply family is covered by the extremely popular plyr package, the base functions remain useful and worth knowing.

    This answer is intended to act as a sort of signpost for new useRs to help direct them to the correct *apply function for their particular problem. Note, this is not intended to simply regurgitate or replace the R documentation! The hope is that this answer helps you to decide which *apply function suits your situation and then it is up to you to research it further. With one exception, performance differences will not be addressed.

    Read the rest at the sourceFrom Stack Overflow: asked by grautur, answered by joran (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.