Skip to content

Cognizant R Programming Interview Questions & Answers

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

About Cognizant hiring for R Programming roles

Cognizant is a US-headquartered IT services and consulting company with most of its workforce based in India. It provides application development, testing, cloud, digital engineering and data analytics services, with strong practices in healthcare, insurance and banking. In India it hires for programmer analyst, quality engineer and data roles through campus and off-campus programmes such as GenC.

For R Programming roles, this Cognizant practice set focuses most on Functions and Functional Programming (6), Modelling and Machine Learning in R (5), Data Structures in R (5), R Basics and Data Types (4). It has 13 easy, 17 medium questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Teaneck, New Jersey, USA
Main India offices
Chennai, Bengaluru, Pune, Hyderabad, Kolkata

Cognizant R Programming interview process

  1. Online assessment (aptitude + reasoning)
  2. Coding assessment
  3. Technical interview
  4. HR round

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

Solved for CognizantStart 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

Explain for, while and repeat loops in R.

Save to ▾
Show answer
A for loop iterates over elements of a vector, for (i in seq_along(x)), and is used when the number of iterations is known. A while loop runs while a condition stays TRUE, useful for convergence or polling. repeat runs indefinitely until break is called. next skips to the next iteration. In R, loops are fine when each iteration is heavy, but for element-wise work vectorized functions or purrr::map() are usually faster and cleaner.
02

How do you build a logistic regression model for churn in R?

Save to ▾
Show answer
Use glm() with family = binomial; predictions with type = 'response' are probabilities. fit <- glm(churned ~ tenure + monthly_charges + contract, data = train, family = binomial) summary(fit) exp(coef(fit)) # odds ratios test$prob <- predict(fit, newdata = test, type = 'response') test$pred <- ifelse(test$prob > 0.5, 1, 0) table(actual = test$churned, predicted = test$pred)
03

Why should R projects use Git and how does RStudio support it?

Save to ▾
Show answer
Git tracks every change to code, lets you revert mistakes, work on branches and collaborate through pull requests and reviews. RStudio has a built-in Git pane to stage, commit, diff, pull and push, and usethis::use_git() and use_github() set up repositories. Keep data files, secrets and outputs out of Git with .gitignore, commit the renv.lock file and write clear commit messages. Version control is expected even for analysis work.
04

What is the difference between [ ], [[ ]] and $ when subsetting?

Save to ▾
Show answer
For lists, [ ] returns a sub-list, while [[ ]] and $ return the element itself. So lst['a'] is a list of length one and lst[['a']] is the value. $ allows partial name matching and cannot take a variable, while [[ ]] accepts a string variable like lst[[col]]. On data frames, df['x'] returns a one-column data frame, and df[['x']] or df$x returns a vector. Think of [ ] as the train car and [[ ]] as its contents.
05

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.
06

Explain the apply family of functions in R.

Save to ▾
Show answer
apply() works over rows or columns of a matrix, lapply() applies a function to each element of a list and returns a list, sapply() simplifies the result to a vector or matrix when possible, vapply() is like sapply() but requires a declared output type, making it safer, and mapply() iterates over several vectors in parallel. tapply() applies a function by groups. For example, sapply(df, class) returns the class of each column.
07

What is Shiny and how is a Shiny app structured?

Save to ▾
Show answer
Shiny is an R package for building interactive web applications without writing HTML or JavaScript. An app has a ui that defines layout and inputs such as dropdowns and sliders, and a server function that contains R logic and creates outputs such as plots and tables. shinyApp(ui, server) runs the app. Analytics teams use Shiny for internal dashboards, what-if calculators and tools that let business users explore data.
08

What is a data frame in R?

Save to ▾
Show answer
A data frame is a list of equal-length vectors, where each vector is a column with its own type. It is R's main structure for tabular data, similar to a spreadsheet or SQL table. str(df) shows column types, nrow() and ncol() give dimensions and summary() gives quick statistics. Tibbles from the tidyverse are modern data frames that print neatly, never convert strings to factors and do not partially match column names.
09

Tell me about feedback you received in a code review and what you changed.

Save to ▾
Show answer
Situation: in my first quarter, a senior reviewed my R reporting script. Task: address the review comments. Action: the main feedback was that my 300-line script mixed data loading, cleaning and plotting with repeated code. I split it into small functions, added input checks and moved constants to a config file. Result: the next report took half the time to build, and I now structure every new script this way from the start.
10

A loop that adds rows to a data frame with rbind() takes very long. How do you speed it up?

Save to ▾
Show answer
Calling rbind() inside a loop copies the growing data frame each iteration, so time grows roughly quadratically. I instead store each piece in a preallocated list, results[[i]] <- piece, and combine once at the end with dplyr::bind_rows() or data.table::rbindlist(), which is the fastest. Better still is to vectorize the computation or use purrr::map() followed by list_rbind(). On 10,000 iterations this can cut runtime from minutes to seconds.
11

Explain the confusion matrix and the metrics derived from it.

Save to ▾
Show answer
A confusion matrix compares actual and predicted classes: true positives, false positives, true negatives and false negatives. Accuracy is the share of correct predictions. Precision is TP / (TP + FP), how many predicted positives are correct. Recall is TP / (TP + FN), how many actual positives were found. F1 is their harmonic mean. For a loan default model, recall matters if missing defaulters is costly; precision matters if rejecting good customers is costly.
12

Describe a time you found a data quality issue in your analysis.

Save to ▾
Show answer
Situation: while preparing a monthly revenue dashboard, totals were 8 percent higher than finance figures. Task: find the cause before the review meeting. Action: I traced row counts after each step in my R script and found a join on customer ID that duplicated rows because some customers had two active addresses. I deduplicated the address table and added a row-count check. Result: numbers matched finance, and the check now runs in every refresh.
13

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)
14

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')
15

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.
16

Write dplyr code to find total and average sales by city, sorted by total.

Save to ▾
Show answer
Group, summarise and sort: library(dplyr) city_summary <- sales %>% filter(!is.na(amount)) %>% group_by(city) %>% summarise( orders = n(), total = sum(amount), avg_order = mean(amount), .groups = 'drop' ) %>% arrange(desc(total)) head(city_summary, 10)
17

Reading a 2 GB CSV file with read.csv() is very slow. What would you do?

Save to ▾
Show answer
read.csv() is single-threaded and guesses types slowly. I would switch to data.table::fread() or readr::read_csv(), which are many times faster and multi-threaded. I would read only the needed columns with the select argument and set column types explicitly. If the file is reused, I convert it once to a binary format like Parquet with the arrow package, which loads in seconds and supports reading just a subset of columns.
18

You ran an A/B test on a checkout page: 4.1 percent conversion versus 4.6 percent. How do you decide if the difference is real?

Save to ▾
Show answer
Conversion is a proportion, so I use a two-proportion test: prop.test(c(conv_a, conv_b), c(n_a, n_b)). I check the p-value and, more importantly, the confidence interval for the difference. Before trusting it, I confirm the sample size was planned in advance, the test ran for full weeks to cover weekday effects, users were randomized properly and nobody stopped the test early when results looked good. Then I judge business significance.
19

What is R and why is it popular for data analysis?

Save to ▾
Show answer
R is an open-source language and environment built for statistics, data analysis and graphics. It is popular because of CRAN, which hosts over 20,000 packages, strong visualization with ggplot2 and built-in statistical functions. Analysts, biostatisticians and data scientists use it for reporting, modelling and research. For example, a pharma analytics team may use R for clinical trial analysis because many statistical methods are first released as R packages.
20

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.
21

How do you customise scales, labels and themes in ggplot2?

Save to ▾
Show answer
Scales control how data maps to visuals, and themes control non-data elements. p + scale_y_continuous(labels = scales::label_percent()) + scale_fill_brewer(palette = 'Set2') + labs(title = 'Conversion by Channel', subtitle = 'FY 2025-26', caption = 'Source: CRM') + theme_minimal(base_size = 12) + theme(legend.position = 'bottom', plot.title = element_text(face = 'bold'), panel.grid.minor = element_blank())
22

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.
23

How do you write a function in R with default arguments?

Save to ▾
Show answer
A function is created with the function keyword and returns the value of its last expression, or an explicit return(). gst_price <- function(price, rate = 0.18, round_to = 2) { if (!is.numeric(price)) stop('price must be numeric') round(price * (1 + rate), round_to) } gst_price(1000) # 1180 gst_price(1000, rate = 0.05) gst_price(c(100, 250)) # vectorized
24

How do you interpret the summary output of an lm() model?

Save to ▾
Show answer
Each coefficient is the expected change in the outcome for a one-unit increase in that predictor, holding others constant. The p-value tests whether the coefficient differs from zero. R-squared is the share of variance explained, and adjusted R-squared penalizes extra predictors. Residual standard error shows typical prediction error in outcome units. The F-statistic tests whether the model beats an intercept-only model. For factors, coefficients are differences from the reference level.
25

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.
26

How do you debug an R function?

Save to ▾
Show answer
After an error, traceback() shows the call stack so I can see which function failed. I insert browser() inside a function to pause execution and inspect variables interactively, stepping with n and continuing with c. debug(fn) or debugonce(fn) enters the browser on the next call without editing code. options(error = recover) lets me choose a frame to inspect after an error. RStudio breakpoints offer the same features visually.
27

The same 40 lines of cleaning code are copied into ten scripts. What would you do?

Save to ▾
Show answer
I would extract the logic into well-named functions with arguments for the parts that differ, then move them into one shared file loaded with source() or, better, a small internal R package. A package gives documentation with roxygen2, tests with testthat and versioning, so every script uses the same tested logic. Fixing a bug then happens in one place. I would migrate the scripts gradually and compare outputs to confirm nothing changed.
28

How do you split one column into several, or combine columns into one?

Save to ▾
Show answer
tidyr provides separate_wider_delim() to split and unite() to combine. library(tidyr) df <- tibble(full_name = c('Amit Kumar', 'Neha Singh'), dob = c('12-05-1999', '03-11-2000')) df %>% separate_wider_delim(full_name, delim = ' ', names = c('first', 'last')) df %>% separate_wider_delim(dob, '-', names = c('d', 'm', 'y')) %>% unite('dob_iso', y, m, d, sep = '-')
29

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.
30

What are the main dplyr verbs?

Save to ▾
Show answer
dplyr has a small set of verbs for data transformation: filter() keeps rows that meet conditions, select() picks columns, mutate() creates or changes columns, arrange() sorts rows, summarise() reduces groups to summary rows and group_by() defines groups for the next operations. Others include distinct(), rename(), relocate(), count() and slice(). Each takes a data frame as the first argument and returns a data frame, so verbs chain naturally with the pipe.

Tips to crack the Cognizant R Programming interview

  • Understand the GenC, GenC Next and GenC Elevate tracks so you know which skills and coding level each role expects.
  • Revise SQL queries, OOP concepts and basic testing terminology since many freshers are placed in development or QA projects.
  • Read about Cognizant's healthcare and life sciences domain work, which is a large part of its client base.
  • 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; Cognizant interviewers usually ask follow-ups on your first answer.

Frequently asked questions

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

Candidates usually go through 4 stages: Online assessment (aptitude + reasoning); Coding assessment; Technical interview; 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 Cognizant R Programming interview?

This practice set leans on Functions and Functional Programming (6), Modelling and Machine Learning in R (5), Data Structures in R (5), R Basics and Data Types (4). Revise those first, then practise explaining one or two of your own projects end to end, because most Cognizant interviewers ask you to walk through real work.

Are these the exact questions asked at Cognizant?

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

Where does Cognizant hire R Programming professionals in India?

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

R Programming questions for similar companies