# 50+ Best Data Science with R Interview Questions and Answers

Last updated on 17th Nov 2021, Blog, Interview Questions

These Data Science with R Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Data Science with R. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer.we are going to cover top 100 Data Science with R Interview questions along with their detailed answers. We will be covering Data Science with R scenario based interview questions, Data Science with R interview questions for freshers as well as Data Science with R interview questions and answers for experienced.

**1.Explain about data import in R language. **

**Ans:**

- Users can select the data set in the dialog box or enter the name of the data set (if they know).
- Data can also be entered directly using the editor of R Commander via Data->New Data Set. However, this works well when the data set is not too large.
- Data can also be imported from a URL or from a plain text file (ASCII), from any other statistical package or from the clipboard.

R Commander is used to import data in R language. To start the R commander GUI, the user must type in the command Rcmdr into the console. There are 3 different ways in which data can be imported in R language:-

**2.Two vectors X and Y are defined as follows – X <- c(3, 2, 4) and Y <- c(1, 2). What will be output of vector Z that is defined as Z <- X*Y. **

**Ans:**

In R language when the vectors have different lengths, the multiplication begins with the smaller vector and continues till all the elements in the larger vector have been multiplied.The output of the above code will be – Z <- (3, 4, 4)

**3.How missing values and impossible values are represented in R language? **

**Ans:**

NaN (Not a Number) is used to represent impossible values whereas NA (Not Available) is used to represent missing values. The best way to answer this question would be to mention that deleting missing values is not a good idea because the probable cause for missing value could be some problem with data collection or programming or the query. It is good to find the root cause of the missing values and then take necessary steps handle them.

**4. R language has several packages for solving a particular problem. How do you make a decision on which one is the best to use? **

**Ans:**

CRAN package ecosystem has more than 6000 packages. The best way for beginners to answer this question is to mention that they would look for a package that follows good software development principles. The next thing would be to look for user reviews and find out if other data scientists or analysts have been able to solve a similar problem.

**5.Which function in R language is used to find out whether the means of 2 groups are equal to each other or not? **

**Ans:**

t.tests ()

**6.What is the best way to communicate the results of data analysis using R language? **

**Ans:**

The best possible way to do this is combine the data, code and analysis results in a single document using knitr for reproducible research. This helps others to verify the findings, add to them and engage in discussions. Reproducible research makes it easy to redo the experiments by inserting new data and applying it to a different problem.

**7.How many data structures does R language have? **

**Ans:**

R language has Homogeneous and Heterogeneous data structures. Homogeneous data structures have same type of objects – Vector, Matrix ad Array. Heterogeneous data structures have different type of objects – Data frames and lists.

**8.Explain about the significance of transpose in R language. **

**Ans:**

Transpose t () is the easiest method for reshaping the data before analysis.

**9.What are with () and BY () functions used for? **

**Ans:**

With () function is used to apply an expression for a given dataset and BY () function is used for applying a function each level of factors.

**10.dplyr package is used to speed up data frame management code. Which package can be integrated with dplyr for large fast tables? **

**Ans:**

data.table

**11.In base graphics system, which function is used to add elements to a plot? **

**Ans:**

boxplot () or text ()

**12.What are the different type of sorting algorithms available in R language? **

**Ans:**

- Bucket Sort.
- Selection Sort.
- Quick Sort.
- Bubble Sort.
- Merge Sort.

**13.What is the command used to store R objects in a file? **

**Ans:**

save (x, file=”x.Rdata”)

**14.What is the best way to use Hadoop and R together for analysis? **

**Ans:**

HDFS can be used for storing the data for long-term. MapReduce jobs submitted from either Oozie, Pig or Hive can be used to encode, improve and sample the data sets from HDFS into R. This helps to leverage complex analysis tasks on the subset of data prepared in R.

**15.What will be the output of log (-5.8) when executed on R console? **

**Ans:**

Executing the above on R console will display a warning sign that NaN (Not a Number) will be produced because it is not possible to take the log of negative number.

**16.How is a Data object represented internally in R language? **

**Ans:**

unclass (as.Date (“2016-10-05″))

**17.Which package in R supports the exploratory analysis of genomic data? **

**Ans:**

Adegenet

**18.What is the difference between data frame and a matrix in R? **

**Ans:**

Data frame can contain heterogeneous inputs while a matrix cannot. In matrix only similar data types can be stored whereas in a data frame there can be different data types like characters, integers or other data frames.

**19.How can you add datasets in R? **

**Ans:**

rbind () function can be used add datasets in R language provided the columns in the datasets should be same.

**20.What are factor variable in R language? **

**Ans:**

Factor variables are categorical variables that hold either string or numeric values. Factor variables are used in various types of graphics and particularly for statistical modelling where the correct number of degrees of freedom is assigned to them.

**21.What is the memory limit in R? **

**Ans:**

8TB is the memory limit for 64-bit system memory and 3GB is the limit for 32-bit system memory.

**22.What are the data types in R on which binary operators can be applied? **

**Ans:**

Scalars, Matrices ad Vectors.

**23.How do you create log linear models in R language? **

**Ans:**

Using the loglm () function

**24.What is meant by K-nearest neighbour? **

**Ans:**

K-Nearest Neighbour is one of the simplest machine learning classification algorithms that is a subset of supervised learning based on lazy learning. In this algorithm the function is approximated locally and any computations are deferred until classification.

**25.What will be the class of the resulting vector if you concatenate a number and a character? **

**Ans:**

Character

**26.How can you debug and test R programming code? **

**Ans:**

R code can be tested using Hadley’s testthat package.

**27.Write a function in R language to replace the missing value in a vector with the mean of that vector. **

**Ans:**

mean impute <- function(x) {x [is.na(x)] <- mean(x, na.rm = TRUE); x}

**28.What happens if the application object is not able to handle an event? **

**Ans:**

The event is dispatched to the delegate for processing.

**29.Differentiate between lapply and sapply. **

**Ans:**

- If the programmers want the output to be a data frame or a vector, then sapply function is used whereas if a programmer wants the output to be a list then lapply is used.
- There one more function known as vapply which is preferred over sapply as vapply allows the programmer to specific the output type.
- The disadvantage of using vapply is that it is difficult to be implemented and more verbose.

**30.Differentiate between seq (6) and seq_along (6) **

**Ans:**

Seq_along(6) will produce a vector with length 6 whereas seq(6) will produce a sequential vector from 1 to 6 c( (1,2,3,4,5,6)).

**31.How do you write R commands? **

**Ans:**

The line of code in R language should begin with a hash symbol (#).

**32.How can you verify if a given object “X” is a matric data object? **

**Ans:**

If the function call is.matrix(X ) returns TRUE then X can be termed as a matrix data object.

**33.What do you understand by element recycling in R? **

**Ans:**

If two vectors with different lengths perform an operation –the elements of the shorter vector will be re-used to complete the operation. This is referred to as element recycling.

**34.How can you verify if a given object “X” is a matrix data object? **

**Ans:**

If the function call is.matrix(X) returns true then X can be considered as a matrix data object otheriwse not.

**35.How will you measure the probability of a binary response variable in R language? **

**Ans:**

Logistic regression can be used for this and the function glm () in R language provides this functionality.

**36.What is the use of sample and subset functions in R programming language? **

**Ans:**

- Sample () function can be used to select a random sample of size ‘n’ from a huge dataset.
- Subset () function is used to select variables and observations from a given dataset.

**37.There is a function fn(a, b, c, d, e) a + b * c – d / e. Write the code to call fn on the vector c(1,2,3,4,5) such that the output is same as fn(1,2,3,4,5). **

**Ans:**

do.call (fn, as.list(c (1, 2, 3, 4, 5)))

**38.How can you resample statistical tests in R language? **

**Ans:**

Coin package in R provides various options for re-randomization and permutations based on statistical tests. When test assumptions cannot be met then this package serves as the best alternative to classical methods as it does not assume random sampling from well-defined populations.

**39.What is the purpose of using Next statement in R language? **

**Ans:**

If a developer wants to skip the current iteration of a loop in the code without terminating it then they can use the next statement. Whenever the R parser comes across the next statement in the code, it skips evaluation of the loop further and jumps to the next iteration of the loop.

**40.How will you check if an element 25 is present in a vector? **

**Ans:**

- It can be done using the match () function- match () function returns the first appearance of a particular element.
- The other is to use %in% which returns a Boolean value either true or false.
- Is.element () function also returns a Boolean value either true or false based on whether it is present in a vector or not.

There are various ways to do this:-

**41.What is the difference between library() and require() functions in R language? **

**Ans:**

There is no real difference between the two if the packages are not being loaded inside the function. require () function is usually used inside function and throws a warning whenever a particular package is not found. On the flip side, library () function gives an error message if the desired package cannot be loaded.

**42.What are the rules to define a variable name in R programming language? **

**Ans:**

A variable name in R programming language can contain numeric and alphabets along with special characters like dot (.) and underline (-). Variable names in R language can begin with an alphabet or the dot symbol. However, if the variable name begins with a dot symbol it should not be a followed by a numeric digit.

**43.What do you understand by a workspace in R programming language? **

**Ans:**

The current R working environment of a user that has user defined objects like lists, vectors, etc. is referred to as Workspace in R language.

**44.Which function helps you perform sorting in R language? **

**Ans:**

Order ()

**45.How will you list all the data sets available in all R packages? **

**Ans:**

Using the below line of code- data(package = .packages(all.available = TRUE))

**46.Which function is used to create a histogram visualisation in R programming language? **

**Ans:**

Hist()

**47.Write the syntax to set the path for current working directory in R environment. **

**Ans:**

Setwd(“dir_path”)

**48.What will be the output of runif (7)? **

**Ans:**

It will generate 7 randowm numbers between 0 and 1.

**49.What is the difference between rnorm and runif functions ? **

**Ans:**

rnorm function generates “n” normal random numbers based on the mean and standard deviation arguments passed to the function.

**50.How will you combine multiple different string like “Data”, “Science”, “in” ,“R”, “Programming” as a single string “Data_Science_in_R_Programmming” ? **

**Ans:**

paste(“Data”, “Science”, “in” ,“R”, “Programming”,sep=”_”)

**51.Write a function to extract the first name from the string “Mr. Tom White”. **

**Ans:**

substr (“Mr. Tom White”,start=5, stop=7)

**52.What is R Base package? **

**Ans:**

R Base package is the package that is loaded by default whenever R programming environent is loaded .R base package provides basic fucntionalites in R environment like arithmetic calcualtions, input/output.

**53.What will be the result of multiplying two vectors in R having different lengths? **

**Ans:**

The multiplication of the two vectors will be performed and the output will be displayed with a warning message like – “Longer object length is not a multiple of shorter object length.” Suppose there is a vector a<-c (1, 2, 3) and vector b <- (2, 3) then the multiplication of the vectors a*b will give the resultant as 2 6 6 with the warning message. The multiplication is performed in a sequential manner but since the length is not same, the first element of the smaller vector b will be multiplied with the last element of the larger vector a.

**54.R programming language has several packages for data science which are meant to solve a specific problem, how do you decide which one to use? **

**Ans:**

CRAN package repository in R has more than 6000 packages, so a data scientist needs to follow a well-defined process and criteria to select the right one for a specific task. When looking for a package in the CRAN repository a data scientist should list out all the requirements and issues so that an ideal R package can address all those needs and issues.

**55.How can you merge two data frames in R language? **

**Ans:**

Data frames in R language can be merged manually using cbind () functions or by using the merge () function on common rows or columns.

**56.How will you convert a factor variable to numeric in R language ? **

**Ans:**

A factor variable can be converted to numeric using the as.numeric() function in R language. However, the variable first needs to be converted to character before being converted to numberic because the as.numeric() function in R does not return original values but returns the vector of the levels of the factor variable. X <- factor(c(4, 5, 6, 6, 4)) X1 = as.numeric(as.character(X))

**57.Explain the significance of R programming language for Data Science ? **

**Ans:**

- Most of the calculations can be done with the help of vector so it is easy for data scientists to add functions to a single vector without having to put them in a loop.
- A turning complete language that can be used for any kind of data science task whether it is in the field of genetics, statistics or biology.
- Being an interpreted language , it does not require any compiler-making development of code easier.

**58.What is power analysis ? **

**Ans:**

Power analysis is the process used to determine the effect of a given sample size and is generally used for experimental design.Pwr package in R is used for power analysis.

**59.What is the usage of lattice package in R ? **

**Ans:**

Lattice package helps enhance base R graphics by providing better defaults and helps easily display multi-variate relationships.

**60.What is the need of factorizing variables in R? **

**Ans:**

When performing machine learning tasks, it is important that categorical variables like gender, countries, etc. are converted into numbers. In R, we thus use the factor function to make our categorical variables algorithm-friendly.

**61.dplyr <- "ggplot2" library(dplyr). Which package will be loaded on executing the command and why? **

**Ans:**

Upon executing the mentioned command, the tidyverse package will be loaded as both ggplot2 and dplyr are included in the tidyverse package collection.

**62.Why you should use R language for statistical work? **

**Ans:**

The programing language R is used for statistical analysis as it is an interpreted language that offers several packages that contain statistical functions.

**63.What according to you are disadvantages of R Programming over Python?**

**Ans:**

- The userbase of Python is larger than that of R Programming Language. Thus, the bugs are resolved relatively quickly for Python than R.
- Certain calculations in R aren’t as quick as Python because of its syntax.
- It is not as good as Python when it comes to Data Manipulation and Data Visualization tasks.

**64.How can you develop a package in R language and do version control? **

**Ans:**

This list of 100 data science interview questions is not an exhaustive one and we know that we have not gotten all the answers here. We request the data science community to help us out with the questions that we did not get the answers to. Please do chime in with any data science interview questions related to R programming that you think ought to be here. We will add it in.

**65.How will you save the output of an R plot? **

**Ans:**

To create a pdf, you can use the pdf() function, and if one wishes to save the plot in jpeg format, they can use the jpeg() function.

**66.What do (principal) diagonal and non diagonal elements of a confusion matrix printed using table() function in R represent? **

**Ans:**

The diagonal elements of the confusion matrix represent correct predictions for a given target variable while the non-diagonal elements represent incorrect predictions.

**67.How many inputs does knn() function of the class library in R require? Explain each of them briefly. **

**Ans:**

- A matrix that consists of feature values from the training data.
- A matrix that consists of feature values from testing data, for which we want to make predictions.
- A vector that contains target values or class labels for the training data.
- A value of K that specifies the number of nearest neighbors to be used by the algorithm.

The knn() function requires following four inputs:-

**68.What is Rmarkdown? **

**Ans:**

RMarkdown is a reporting tool provided by R. With the help of Rmarkdown, you can create high quality reports of your R code.

**69.What is the use of the set.seed() function? **

**Ans:**

The set.seed() function is used by R programmers to set a seed for the language’s random number generator. This means that the function will allow users to reproduce the same results as observed by someone who uses the same code even if they have used a random number generator in their code.

**70.If you use glm() function to fit a model without providing a value for the family argument, which regression model will be used by the R Programming language? **

**Ans:**

The model used by the language will be the linear regression model and the function glm() will perform in the same manner as the lm() functions.

**71.Which library has the cross-validation function cv.glm()? **

**Ans:**

The Boot library.

**72.Write the code to remove rows that contain missing values for any variable in the dataset ‘Hello.csv’. **

**Ans:**

- Hello = read.table(“Hello.csv”)
- Hello = na.omit(Hello)

Assuming that we are working the correct directory which contains ‘Hello.csv’, the following code should work:-

**73.What criteria does regsubsets() function of the ‘leaps’ library use to perform best subset selection? **

**Ans:**

The function regsubsets() evaluates the best subset selection by choosing the best model that has a given number of feature variables, where best is quantified using the residual sum-of-squares (RSS).

**74.Which function is used to perform both ridge regression and lasso regression? By default, which regression does it perform? **

**Ans:**

Both ridge regression and lasso regression can be performed using the function glmnet() of the glmnet package. By default, the glmnet() function performs ridge regression for a predefined range of λ values.

**75.What does setting the argument TRUE for the scale variable of pcr() function do? **

**Ans:**

On setting the value of scale as TRUE, we will observe that each feature variable will be standardized or normalized, before evaluating the principal components. This is done so that scale of each feature variable can be ignored while analyzing the significance of each one.

**76.What does the percentage of variance for different datasets prepared by selecting different numbers of components using Principal Component Analysis (PCA) reflect? **

**Ans:**

- N=1 conveys 40% of all the variance,
- N=4 conveys 80% of all the variance,
- And N= total number of feature variables conveys 100% of the variance as the full dataset has been covered.

The percentage variance for different datasets prepared through PCA reflects the amount of information about the feature variables or the target variable that has been conveyed by selecting N number of principal components. For example: Given a dataset, we observe

**77.Given a decision tree in R, ‘tree.vehicles’, how will you display the tree in R? **

**Ans:**

We can use plot() function to visualize the structure of the decision tree. Along with this function, we can use text() function to show the node labels. And if we set pretty=0, we can also see full category names of any qualitative feature variable instead of just displaying an initial for each category.

**78.When you print the summary() for a classification decision tree, you will notice a parameter ‘deviance’. What is it and what does it denote? **

**Ans:**

Deviance is a metric for estimating the performance of a classification decision tree. It is given by,where nmk is the number of observations in the mth terminal node that belongs to the kth class.

**79.Can the random forest function be used for both bagging and random forests? If yes, how? **

**Ans:**

Yes, the random forest function can be used for both bagging and random forests by setting the values for the parameter mtry.

**80.How are node impurity measures different for classification decision trees and regression decision trees? **

**Ans:**

For classification decision trees, the node impurity is evaluated using Residual sum-of-squares and the node impurity of regression decision trees is evaluated using deviance.

**81.How are node impurity measures different for classification decision trees and regression decision trees? **

**Ans:**

For classification decision trees, the node impurity is evaluated using Residual sum-of-squares and the node impurity of regression decision trees is evaluated using deviance.

**82.Which library of R contains the Support Vector Classifier? **

**Ans:**

The library e1071 has the function svm() that can be used to implement the Support Vector Classifier by setting the argument kernel=”linear”.

**83.What is the cost argument for a Support Vector Classifier? **

**Ans:**

A cost argument is a tool for specifying the cost of a violation to the margin. When the cost argument takes a small value, the margins for the classifier are wide and several support vectors lie on the margin or violate the margin. When the cost argument takes a large value, then the margins for the support vectors are narrow, and very few support vectors are on the margin or violate the margin.

**84.What happens when we set the argument “scale=FALSE” for the svm() function? **

**Ans:**

The argument “scale=FALSE” ensures that the function does not scale each feature variable in a way that they have mean zero or standard deviation one. If one wants their feature variables scaled in this manner, then they should use “scale=TRUE”.

**85.Which function of the e1071 library is used to perform cross-validation for the Support Vector Classifier? How many folds are there by default for cross-validation? **

**Ans:**

The function tune() of the e1071 library is used to perform cross-validation. By default, it performs ten-fold cross-validation on a given dataset.

**86.How will you implement Support Vector Machine in R? Explain for both radial and polynomial kernel. **

**Ans:**

Using the svm() function of the e1071 library, we can implement a support vector machine (SVM) in R. It has a parameter kernel that we can set the values for to use SVM with a polynomial or radial kernel. For using the SVM with a polynomial kernel, we set kernel=”polynomial” and for using the SVM with a radial kernel, we set kernel=”radial”. For the former case, we specify the degree of a polynomial by providing the value of the degree argument and for the latter case, we specify the value for γ for the radial basis kernel by providing the value for the gamma argument.

**87.Write the code to print the mean of the feature variables for the USArrests data which is a part of the base R package. **

**Ans:**

apply(USArrests, 2, mean) The second input to the function has been used to specify that the mean has to be evaluated column-wise.

**88.What is the significance of the “nstart” argument for the kmeans() function? **

**Ans:**

The nstart argument for the kmeans() function allows us to run the K-means clustering algorithm with multiple initial cluster assignments. If the argument nstart is provided with a value greater than one, then the K-means clustering will be performed using multiple random assignments, and the function kmeans() will display only the best results. It is thus always recommended to use a large value for the nstart argument as otherwise, an undesirable local optimum may be obtained.

**89.How will you make sure that the results that you have obtained using the K-means clustering algorithms are reproducible? **

**Ans:**

To ensure reproducible results, we will set a random seed using the set.seed() function.

**90.List a few string manipulation functions in the R language. **

**Ans:**

- nchar()
- grep()
- paste()
- substr()
- strsplit()
- gregexpr()
- regex()
- sprintf()

Here a few functions available in R Language that allow string manipulation:-

**91.Explain the usage of abline() function. **

**Ans:**

abline function in R used to add reference line to a graph. Below is the syntax of using abline function – abline(h=yvalues, v=xvalues)

**92.Explain the usage of which() function in R language. **

**Ans:**

- which() function determines the postion of elemnts in a logical vector that are TRUE.
- In the below example, we are finding the row number wherein the maximum value of variable v1 is recorded.
- mydata=data.frame(v1 = c(2,4,12,3,6)) which(mydata$v1==max(mydata$v1))
- It returns 3 as 12 is the maximum value and it is at 3rd row in the variable x=v1.

**93.What is the procedure to check the cumulative frequency distribution of any categorical variable? **

**Ans:**

The cumulative frequency distribution of a categorical variable can be checked using the cumsum () function in R language.

**94.Can you tell if the equation given below is linear or not ? **

**Ans:**

Emp_sal= 2000+2.5(emp_age)2 Yes it is a linear equation as the coefficients are linear.

**95.How will you create scatterplot matrices in R language? **

**Ans:**

- formula- A formula basically like ~a+b+c . Each term gives a separate variable in the pairs plots where the terms should be numerical vectors. It basically represents the series of variables used in pairs.
- data- It basically represents the dataset from which the variables have to be taken for building a scatterplot.

A matrix of scatterplots can be produced using pairs. Pairs function takes various parameters like formula, data, subset, labels, etc.The two key parameters required to build a scatterplot matrix are:-

**Data Scientist Sample Resumes! Download & Edit, Get Noticed by Top Employers!**Download

**96.What is the value of f (2) for the following R code? **

**Ans:**

- b <- 4
- f <- function (a)
- {
- b <- 3
- b^3 + g (a)
- }
- g <- function (a)
- {
- *b
- }

**97.Compare R and Python programming languages for Predictive Modelling. **

**Ans:**

Model Building. | Both are Similar. | Both are Similar. |

Model Interpretability. | Not better than R. | R is better. |

Production. | Python is Better. | Not better than Python. |

Community Support. | Not better than R. | R has good community support over Python. |

Data Science Libraries. | Both are similar. | Both are similar. |

Data Visualizations. | Not better than R. | R has good data visualizations libraries and tools. |