Skip to content

TCS R Programming Interview Questions & Answers

Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.

About TCS hiring for R Programming roles

Tata Consultancy Services is a Tata Group company and one of the largest IT services and consulting firms in the world. It delivers application development, testing, cloud, data and analytics services to clients in banking, retail, manufacturing and other industries. In India it hires freshers and experienced staff for software testing, data engineering, BI reporting and analytics roles across its delivery centres.

For R Programming roles, this TCS practice set focuses most on Modelling and Machine Learning in R (6), R Basics and Data Types (5), Reports, Shiny and Production R (5), Data Visualization with ggplot2 (4). It has 10 easy, 19 medium, 1 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Mumbai, India
Main India offices
Mumbai, Chennai, Pune, Bengaluru, Hyderabad

TCS R Programming interview process

  1. TCS NQT online assessment (aptitude + coding)
  2. Technical interview
  3. Managerial round
  4. HR round

Typical pattern based on public candidate experiences. Rounds vary by role, team and year.

Solved for TCSStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What are the atomic data types in R?

Save to ▾
Show answer
R has six atomic types: logical (TRUE/FALSE), integer (5L), double or numeric (3.14), character ('text'), complex (2+3i) and raw (bytes). typeof() returns the internal type while class() returns the class attribute used for method dispatch. For example, typeof(5) is 'double' but typeof(5L) is 'integer'. Knowing types matters because mixing them in one vector triggers coercion to the most flexible type.
02

What tools does R offer for time series forecasting?

Save to ▾
Show answer
The forecast package provides auto.arima(), ets() for exponential smoothing and easy plotting of forecasts with intervals. The newer tidyverts family, with tsibble for time-series data frames, fable for models and feasts for features and decomposition, works with tidy data and fits many series at once. prophet handles strong seasonality and holidays. Typical steps are visualizing, decomposing trend and seasonality, fitting candidates and comparing accuracy on a holdout period.
03

What do geom_smooth() and stat_summary() do?

Save to ▾
Show answer
geom_smooth() adds a fitted trend line with a confidence band, using loess for small data and a GAM for large data by default, or method = 'lm' for a straight line. stat_summary() computes summaries of y for each x, for example stat_summary(fun = mean, geom = 'point') to plot group means, or fun.data = mean_cl_normal for error bars. Both let you show patterns without precomputing summaries.
04

How do you clean and manipulate text data in R?

Save to ▾
Show answer
The stringr package gives consistent functions starting with str_. library(stringr) x <- c(' Rahul Sharma ', 'priya VERMA') str_trim(x) str_to_title(x) str_detect(x, 'Sharma') str_replace_all('9876-543-210', '-', '') str_extract('Order ID: 45821', '[0-9]+') str_split('a,b,c', ',')[[1]] str_pad('7', width = 3, pad = '0') # '007'
05

Explain the difference between NA, NULL and NaN in R.

Save to ▾
Show answer
NA means a missing value and has a type, such as NA_integer_ or NA_character_. NULL means the absence of an object, has length 0 and disappears when combined with c(). NaN means not a number, the result of undefined maths like 0/0. is.na() returns TRUE for both NA and NaN, while is.nan() is TRUE only for NaN. For example, length(c(1, NULL, 3)) is 2 but length(c(1, NA, 3)) is 3.
06

What is the difference between variance and standard deviation?

Save to ▾
Show answer
Variance is the average squared deviation from the mean, and standard deviation is its square root. Because variance is in squared units, standard deviation is easier to interpret since it uses the same units as the data. In R, var() and sd() both use the sample formula with n - 1 in the denominator. For example, delivery times with mean 30 minutes and SD 5 minutes are far more consistent than with SD 15.
07

Write a recursive function in R to calculate factorial and Fibonacci numbers.

Save to ▾
Show answer
A recursive function calls itself with a smaller input and needs a base case. fact <- function(n) { if (n <= 1) return(1) n * fact(n - 1) } fact(5) # 120 fib <- function(n) { if (n <= 2) return(1) fib(n - 1) + fib(n - 2) } fib(10) # 55 # vectorized and efficient alternative factorial(5); cumprod(1:5)
08

A numeric column in your data has been read as character. How do you fix it?

Save to ▾
Show answer
I first find the offending values, for example with unique(df$amount[is.na(as.numeric(df$amount))]), which reveals entries like '1,200', 'NA ' or '-'. Then I clean them, removing commas with gsub(',', '', x) and spaces with trimws(), and convert with as.numeric(). With readr I can also pass na = c('', '-', 'NA') and col_types so the column is parsed correctly at load time instead of being fixed later.
09

How do you do feature engineering with recipes in tidymodels?

Save to ▾
Show answer
A recipe defines preprocessing steps that are learned on training data and applied identically to new data. rec <- recipe(price ~ ., data = train) %>% update_role(listing_id, new_role = 'id') %>% step_date(listed_on, features = c('month', 'dow')) %>% step_rm(listed_on) %>% step_log(area_sqft) %>% step_other(locality, threshold = 0.01) %>% step_dummy(all_nominal_predictors()) %>% step_normalize(all_numeric_predictors()) prep(rec) %>% bake(new_data = NULL) %>% glimpse()
10

What is a pure function and why prefer them in data pipelines?

Save to ▾
Show answer
A pure function always returns the same output for the same inputs and has no side effects, such as modifying global variables, writing files or printing. Pure functions are easy to test, reuse, cache and run in parallel, because they do not depend on hidden state. In data pipelines, I keep transformations pure, taking a data frame and returning a new one, and isolate side effects such as reading and writing in a few clearly named functions.
11

What is vectorization in R and why does it matter?

Save to ▾
Show answer
Vectorization means applying an operation to a whole vector at once instead of looping over elements. Most R functions, like +, sqrt() and ifelse(), are vectorized and implemented in C, so they are much faster than R-level for loops. For example, prices * 1.18 adds 18 percent GST to every price in one step. Writing vectorized code is the first optimization an R developer should try before parallel processing or Rcpp.
12

Explain Type I and Type II errors.

Save to ▾
Show answer
A Type I error is rejecting a true null hypothesis, a false positive, and its probability is the significance level alpha, usually 0.05. A Type II error is failing to reject a false null hypothesis, a false negative, with probability beta; power is 1 - beta. For example, launching a feature that does not actually help is a Type I error, while dropping a feature that really works is Type II. Larger samples reduce Type II errors.
13

What is the structure of an R package?

Save to ▾
Show answer
A minimal package has a DESCRIPTION file with metadata and dependencies, a NAMESPACE file listing exported functions, an R/ folder with function code, a man/ folder for documentation and usually tests/ for testthat tests. The usethis and devtools packages create and manage this: usethis::create_package(), use_r(), use_test(), and devtools::document(), test() and check(). Documentation is written as roxygen2 comments above each function. Internal packages are ideal for sharing team utilities.
14

What are the assumptions of linear regression?

Save to ▾
Show answer
The main assumptions are a linear relationship between predictors and the outcome, independent errors, constant variance of errors (homoscedasticity), normally distributed errors for valid inference and no severe multicollinearity. In R, plot(fit) shows residuals versus fitted values, a Q-Q plot and leverage, and car::vif() checks collinearity. Violations can be addressed with transformations like log, robust standard errors or different models such as GLMs.
15

What is the difference between Quarto and R Markdown?

Save to ▾
Show answer
Quarto is the next-generation publishing system from Posit. It works with R, Python, Julia and Observable, and is a standalone command-line tool rather than an R package. It uses the same knitr engine for R and similar syntax, with chunk options written as #| comments. Quarto adds consistent support for websites, books, presentations and dashboards. R Markdown is still supported, but new projects increasingly use Quarto, especially in mixed R and Python teams.
16

What is the difference between mapping and setting an aesthetic in ggplot2?

Save to ▾
Show answer
Mapping links an aesthetic to a variable inside aes(), so values change with the data and a legend is created, for example aes(colour = region). Setting fixes an aesthetic to a constant outside aes(), for example geom_point(colour = 'steelblue'). A common mistake is writing aes(colour = 'blue'), which treats 'blue' as a data value, creates a legend called blue and uses the default red colour instead.
17

In your regression, coefficient signs look wrong and standard errors are huge. What might be the problem?

Save to ▾
Show answer
This is a classic sign of multicollinearity, where predictors are highly correlated, for example total spend and online spend. The model cannot separate their effects, so coefficients become unstable. I check correlations and the variance inflation factor with car::vif(); values above 5 or 10 are a concern. Solutions are removing or combining correlated variables, using principal components or ridge regression. Prediction accuracy may be fine, but interpretation is unreliable.
18

What is the difference between <- and = for assignment in R?

Save to ▾
Show answer
Both assign values at the top level, but <- is the conventional assignment operator in R style guides, while = is mainly used to pass named arguments inside function calls. For example, mean(x = 1:10) passes an argument and does not create x in the workspace, but mean(x <- 1:10) creates x as a side effect. Using <- for assignment keeps code readable and avoids confusion between assignment and argument matching.
19

What is renv and why should you use it?

Save to ▾
Show answer
renv is a package that creates a project-specific library and records exact package versions in a renv.lock file. renv::init() sets up the project, renv::snapshot() updates the lockfile and renv::restore() installs the same versions on another machine or server. This prevents code from breaking when packages update, makes analysis reproducible months later and is essential before deploying scripts or Shiny apps to production.
20

How do you add logging to a production R script?

Save to ▾
Show answer
The logger package gives levelled, timestamped logs written to the console or a file. library(logger) log_appender(appender_file('logs/etl.log')) log_threshold(INFO) log_info('ETL started') res <- tryCatch({ df <- load_orders() log_info('Loaded {nrow(df)} rows') df }, error = function(e) { log_error('Load failed: {conditionMessage(e)}') quit(status = 1) }) log_info('ETL finished')
21

What are facets in ggplot2?

Save to ▾
Show answer
Facets split a plot into small multiples, one panel per category, sharing the same axes and geoms. facet_wrap(~ region) wraps panels for one variable, and facet_grid(rows = vars(segment), cols = vars(year)) creates a grid for two variables. scales = 'free_y' lets each panel have its own y-axis. Facets are often clearer than one chart with many overlapping coloured lines, for example comparing sales trends across ten states.
22

What is the difference between errors, warnings and messages in R?

Save to ▾
Show answer
An error, raised with stop(), halts execution because something cannot continue. A warning, raised with warning(), lets code continue but signals a possible problem, such as NAs introduced by coercion. A message, from message(), is informational, such as progress updates. Messages go to stderr, so they can be suppressed with suppressMessages() without hiding results. Use print() or cat() for output the user requested, not for diagnostics.
23

Write a reusable function that summarises any numeric column by any grouping column using dplyr.

Save to ▾
Show answer
Use {{ }} to pass columns into data-masking verbs: library(dplyr) summarise_by <- function(data, group_col, value_col) { data %>% group_by({{ group_col }}) %>% summarise( n = n(), mean_val = mean({{ value_col }}, na.rm = TRUE), total = sum({{ value_col }}, na.rm = TRUE), .groups = 'drop' ) %>% arrange(desc(total)) } summarise_by(sales, city, amount)
24

Explain reactivity in Shiny.

Save to ▾
Show answer
Shiny uses reactive programming: outputs automatically update when the inputs they depend on change. Inputs are reactive sources, outputs such as renderPlot() are reactive endpoints, and reactive() expressions are cached intermediate results that recompute only when their dependencies change. For example, filtering data once in a reactive() and using it in three charts avoids filtering three times. Shiny tracks dependencies automatically, so you do not write explicit event handlers for most cases.
25

What are semi_join() and anti_join() used for?

Save to ▾
Show answer
They are filtering joins: they keep rows of the left table based on matches in the right table but add no columns. semi_join() keeps rows that have a match, and anti_join() keeps rows that have no match. For example, anti_join(customers, orders, by = 'customer_id') lists customers who never ordered. They are also safer than inner joins for filtering, since they never duplicate rows when the right table has repeated keys.
26

Your manager says your charts are confusing. How do you respond?

Save to ▾
Show answer
I would thank them and ask which part was unclear, such as too many colours, missing labels or an unclear message. In my internship this happened with a crowded chart of twelve product lines. I simplified it by highlighting the top three, greying the rest, adding a clear title stating the finding and labelling values directly. My manager found the new version easy to present, and I now review every chart for one clear message.
27

How is a matrix different from a data frame?

Save to ▾
Show answer
A matrix is a two-dimensional atomic vector, so all elements share one type, usually numeric. A data frame allows a different type per column. Matrices are faster for linear algebra, such as %*% multiplication, solve() and distance calculations, while data frames suit mixed real-world data. For example, the output of cor() is a matrix, while customer records with names, dates and amounts belong in a data frame. as.matrix() and as.data.frame() convert between them.
28

What is the difference between %>% and |> in R?

Save to ▾
Show answer
%>% comes from the magrittr package and |> is the native pipe built into R since version 4.1. Both pass the left side as the first argument of the right side, so df |> filter(x > 1) equals filter(df, x > 1). The native pipe is faster and needs no package, but it uses _ as a named placeholder only, while %>% supports the dot placeholder anywhere. New code increasingly uses |>, and both work with dplyr.
29

How do you calculate ROC AUC and plot an ROC curve in R?

Save to ▾
Show answer
yardstick in tidymodels or pROC compute AUC from predicted probabilities. library(yardstick) preds <- tibble(truth = factor(test$churned, levels = c('1', '0')), .pred_1 = test$prob) roc_auc(preds, truth, .pred_1) roc_curve(preds, truth, .pred_1) %>% autoplot() # with pROC library(pROC) r <- roc(test$churned, test$prob) auc(r); plot(r)
30

How do you build a linear regression model in R?

Save to ▾
Show answer
lm() fits linear models using formula syntax; summary() shows coefficients and fit. fit <- lm(sales ~ ad_spend + price + region, data = stores) summary(fit) coef(fit) confint(fit) # 95% CIs for coefficients predict(fit, newdata = new_stores, interval = 'prediction') par(mfrow = c(2, 2)); plot(fit) # diagnostic plots broom::tidy(fit) # coefficients as a tibble

Tips to crack the TCS R Programming interview

  • Practise TCS NQT style numerical, verbal and reasoning sections along with two basic coding problems under strict time limits.
  • Be ready to explain your final-year project, SQL basics and core concepts like OOP, DBMS and software testing life cycle.
  • Read about TCS service lines such as BFSI and its iON and Ignio platforms to answer why you want to join.
  • Keep a one-minute story ready for every project on your CV: problem, your part, tools, result.
  • Practise the hard questions on this page aloud; TCS interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the TCS R Programming interview?

Candidates usually go through 4 stages: TCS NQT online assessment (aptitude + coding); Technical interview; Managerial round; HR round. The exact rounds change with the role, team, location and your experience, so confirm the process with the recruiter.

Which topics should I prepare for the TCS R Programming interview?

This practice set leans on Modelling and Machine Learning in R (6), R Basics and Data Types (5), Reports, Shiny and Production R (5), Data Visualization with ggplot2 (4). Revise those first, then practise explaining one or two of your own projects end to end, because most TCS interviewers ask you to walk through real work.

Are these the exact questions asked at TCS?

No. These are curated practice questions that match the skills and difficulty usually tested in it services interviews like TCS's. They are not a leaked or verified list of past questions.

Where does TCS hire R Programming professionals in India?

TCS has large teams in Mumbai, Chennai, Pune, Bengaluru, Hyderabad. Openings and locations change often, so check the TCS careers page and filter by city and experience.

R Programming questions for similar companies