Skip to content

HSBC R Programming Interview Questions & Answers

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

About HSBC hiring for R Programming roles

HSBC is a global banking group with retail, commercial and wholesale banking operations across Asia, Europe and other regions. Its India technology and global service centres support software development, operations, analytics and risk for the group. It hires for software engineers, testers, data analysts, data engineers and financial crime analysts.

For R Programming roles, this HSBC practice set focuses most on Reports, Shiny and Production R (6), Statistics and Hypothesis Testing (5), Data Wrangling with dplyr and tidyr (4), Functions and Functional Programming (4). It has 5 easy, 22 medium, 3 hard questions, so you can start easy and work up to the harder ones.

Company type
Banking & finance
Headquarters
London, United Kingdom
Main India offices
Hyderabad, Pune, Bengaluru

HSBC R Programming interview process

  1. Online assessment (aptitude + technical)
  2. Technical round
  3. Managerial round
  4. HR round

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

Solved for HSBCStart 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 skewness and kurtosis?

Save to ▾
Show answer
Skewness measures asymmetry of a distribution. Positive or right skew has a long right tail, typical of income and order values, so the mean exceeds the median. Negative skew has a long left tail. Kurtosis measures how heavy the tails are compared with a normal distribution; high kurtosis means more extreme values, common in financial returns. In R, the moments or e1071 packages provide skewness() and kurtosis() functions.
02

How do you create a column with multiple conditions in dplyr?

Save to ▾
Show answer
case_when() evaluates conditions in order and returns the value of the first one that is TRUE; .default handles the rest. customers <- customers %>% mutate(segment = case_when( spend >= 50000 ~ 'Platinum', spend >= 20000 ~ 'Gold', spend >= 5000 & visits > 5 ~ 'Silver', .default = 'Regular' )) # simple two-way split mutate(df, high_value = if_else(spend > 20000, 'Yes', 'No'))
03

How would you impute missing values differently for each group?

Save to ▾
Show answer
I group by the relevant category, such as product category, and replace NAs with that group's median: group_by(category) %>% mutate(price = coalesce(price, median(price, na.rm = TRUE))) %>% ungroup(). Group medians are more realistic than a global value. I also add a flag column marking imputed rows so models and reviewers can see them. If a whole group is missing, I fall back to the overall median, and for important features I consider model-based imputation.
04

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

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()
06

How do you apply the same transformation to many columns in dplyr?

Save to ▾
Show answer
across() applies one or more functions to a set of columns selected with tidyselect helpers. df %>% mutate(across(where(is.character), str_trim)) %>% mutate(across(starts_with('amt_'), ~ round(.x, 2))) df %>% group_by(region) %>% summarise(across(c(sales, profit), list(mean = mean, max = max), .names = '{.col}_{.fn}'))
07

Your function gives correct results when you test it but wrong results in the main script. What could be the cause?

Save to ▾
Show answer
A common cause is that the function reads a variable from the global environment instead of taking it as an argument. During testing that global variable had one value, and in the main script it has another. Lexical scoping finds it silently. I would check the function body for names not defined as arguments or locally, for example using codetools::findGlobals(fn), and pass everything explicitly so the function is self-contained.
08

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

Write ggplot2 code for a monthly sales line chart with points.

Save to ▾
Show answer
A basic time-series line chart: library(ggplot2) ggplot(monthly, aes(x = month, y = sales)) + geom_line(colour = 'steelblue', linewidth = 1) + geom_point(size = 2) + scale_y_continuous(labels = scales::label_comma()) + scale_x_date(date_labels = '%b %Y', date_breaks = '2 months') + labs(title = 'Monthly Sales', x = NULL, y = 'Sales (INR)') + theme_minimal()
10

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
11

How do you reshape data between wide and long formats in R?

Save to ▾
Show answer
tidyr's pivot_longer() turns columns into rows and pivot_wider() does the reverse. library(tidyr) # wide: product, Jan, Feb, Mar long <- sales_wide %>% pivot_longer(cols = Jan:Mar, names_to = 'month', values_to = 'sales') wide <- long %>% pivot_wider(names_from = month, values_from = sales, values_fill = 0)
12

What is data.table and when would you use it?

Save to ▾
Show answer
data.table is a high-performance package for large tabular data. Its syntax DT[i, j, by] means filter rows with i, compute j, grouped by by. It updates columns by reference with :=, avoiding copies, and offers fast keyed joins and fread()/fwrite() for file IO. For example, DT[city == 'Delhi', .(avg_sal = mean(salary)), by = dept] filters and aggregates in one step. It is popular for datasets with tens of millions of rows.
13

How do you find out why your R code is slow?

Save to ▾
Show answer
Measure before optimizing. system.time() gives total time, bench::mark() compares alternatives, and profvis shows which lines consume time and memory. system.time(result <- slow_function(df)) bench::mark( loop = sum_loop(x), vec = sum(x) ) library(profvis) profvis({ out <- clean_data(raw) model <- fit_model(out) })
14

Tell me about a dashboard or app you built in R.

Save to ▾
Show answer
Situation: regional sales managers waited for a weekly emailed PDF and could not drill into their own data. Task: give them self-service access. Action: I built a Shiny app with filters by region, product and period, used pre-aggregated tables for speed and deployed it on the internal server with login. I ran a short demo and gathered feedback. Result: over 40 managers used it weekly, and ad hoc data requests to our team fell by about half.
15

What is plumber in R?

Save to ▾
Show answer
plumber turns R functions into REST API endpoints using special comments. You annotate a function with #* @get /predict and its arguments become query parameters, then run the API with pr_run(). Other systems, such as a Java web app or a Python service, can call the R model over HTTP and receive JSON. It is commonly used to serve model predictions, and it can be deployed in Docker or on Posit Connect.
16

Tell me about a time you had two urgent analysis requests at the same time.

Save to ▾
Show answer
Situation: two managers needed different analyses on the same Friday. Task: deliver both without compromising quality. Action: I asked each what decision the analysis would support and the minimum needed by Friday, reused one cleaned dataset in R for both, and shared a draft of the simpler one on Wednesday for early feedback. Result: both received usable outputs on time, and the fuller version of the second analysis followed on Monday as agreed.
17

How do you validate inputs inside an R function?

Save to ▾
Show answer
Fail early with clear messages using stopifnot(), stop() and match.arg(). summarise_kpi <- function(df, metric = c('revenue', 'orders', 'aov'), min_date = NULL) { stopifnot(is.data.frame(df), nrow(df) > 0) metric <- match.arg(metric) if (!is.null(min_date) && !inherits(min_date, 'Date')) { stop('min_date must be a Date', call. = FALSE) } required <- c('date', metric) missing <- setdiff(required, names(df)) if (length(missing)) stop('Missing columns: ', toString(missing)) # ... compute }
18

Write common data.table operations for filtering, aggregating and joining.

Save to ▾
Show answer
Read, filter, aggregate, add columns by reference and join: library(data.table) DT <- fread('orders.csv') DT[status == 'delivered', .N, by = city] DT[, revenue := qty * price] DT[, .(total = sum(revenue)), by = .(city, month)][order(-total)] customers <- fread('customers.csv') merged <- customers[DT, on = 'customer_id'] fwrite(merged, 'merged.csv')
19

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
20

Product wants to detect a lift in conversion from 5 to 5.5 percent. How many users do you need per group?

Save to ▾
Show answer
I use power analysis before the test starts. In R, power.prop.test(p1 = 0.05, p2 = 0.055, power = 0.8, sig.level = 0.05) gives roughly 31,000 users per group. Smaller lifts need far larger samples, since sample size scales with the inverse square of the effect. I would then convert the sample into test duration using daily traffic, round up to full weeks, and agree on the stopping rule in advance to avoid peeking bias.
21

You notice database passwords hardcoded in a shared R script. What do you do?

Save to ▾
Show answer
I remove them immediately, inform the owner and ask for the password to be rotated, since it may exist in version history. Then I store credentials outside the code, in a user-level .Renviron file read with Sys.getenv(), the keyring package backed by the operating system's credential store, or the server's secret management, such as environment variables in Posit Connect. I make sure .Renviron is listed in .gitignore and scan the repository history.
22

Your scatter plot of 200,000 points looks like a solid blob. How do you fix it?

Save to ▾
Show answer
This is overplotting. I reduce point size and add transparency with geom_point(alpha = 0.1, size = 0.5). Better options are geom_hex() or geom_bin2d(), which show density as colour, or geom_density_2d() contours. I could also plot a random sample for shape and a smoothed trend with geom_smooth() on the full data. If x values are discrete, geom_jitter() spreads points. The goal is to make density visible, not every point.
23

Tell me about a time a production job failed and you had to fix it under pressure.

Save to ▾
Show answer
Situation: the scheduled R job feeding the morning leadership dashboard failed at 6 AM after a source table added a new column type. Task: restore the dashboard before the 9 AM meeting. Action: I checked the logs, identified the parsing error, patched the column specification, reran the job and informed stakeholders of the delay. Afterwards I added schema validation and a failure alert. Result: data was live by 8:30 AM, and similar changes are now caught early.
24

Walk me through an end-to-end machine learning project you have done in R.

Save to ▾
Show answer
Situation: a lending team wanted to reduce early loan defaults. Task: build a default risk score. Action: I cleaned two years of loan data with dplyr, engineered features like EMI to income ratio with recipes, compared logistic regression and ranger in tidymodels using 5-fold cross-validation and chose logistic regression for interpretability with AUC 0.78. Result: the score was used in a pilot, flagging 60 percent of defaulters in the riskiest 20 percent of applicants.
25

The finance team wants the daily output as a formatted Excel file, not a CSV. How do you produce it?

Save to ▾
Show answer
I use openxlsx2 or openxlsx to write a workbook with multiple sheets, formatted headers, number formats for INR, column widths, frozen panes and conditional formatting, all from R. writexl is a lightweight option for plain sheets without formatting. I create a template once with the team's preferred layout and generate the file in the scheduled script, then email or upload it to a shared drive. This removes manual formatting every day.
26

A manager says a test with p = 0.06 proves the change had no effect. How do you respond?

Save to ▾
Show answer
I explain that failing to reject the null is not proof of no effect. A p-value of 0.06 means the evidence is weak or the test was underpowered, and the 0.05 cut-off is a convention, not a law. I would show the confidence interval for the effect, which probably ranges from slightly negative to clearly positive, check whether the sample size met the planned power and suggest extending the test or weighing the decision on cost and risk.
27

Explain the d, p, q and r functions for probability distributions in R.

Save to ▾
Show answer
Each distribution has four functions: d for density, p for cumulative probability, q for quantiles and r for random draws. dnorm(0) # density at 0 pnorm(1.96) # P(Z <= 1.96) = 0.975 qnorm(0.975) # 1.96 rnorm(5, mean = 50, sd = 10) dbinom(3, size = 10, prob = 0.2) # exactly 3 successes ppois(2, lambda = 4) # P(X <= 2) qt(0.975, df = 20) # t critical value
28

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

An R script must run every morning at 7 AM and email a report. How do you schedule it?

Save to ▾
Show answer
On a Linux server I schedule Rscript with cron, for example 0 7 * * * Rscript /path/report.R, and on Windows with Task Scheduler or the taskscheduleR package. Posit Connect can schedule Quarto reports and email them directly. GitHub Actions can run scheduled workflows for non-sensitive jobs. The script itself renders the report and sends it with blastula or emayili. I add logging and an alert on failure so silent misses are caught.
30

What does a 95 percent confidence interval mean?

Save to ▾
Show answer
If we repeated the sampling many times and built an interval each time, about 95 percent of those intervals would contain the true population value. It does not mean there is a 95 percent probability that this specific interval contains it. A narrow interval shows precise estimation and a wide one shows uncertainty. For example, average order value of 850 INR with CI 820 to 880 is far more useful than CI 600 to 1100.

Tips to crack the HSBC R Programming interview

  • Learn anti-money laundering and KYC basics, since financial crime analytics is a large function at HSBC.
  • Revise SQL, Python and testing fundamentals for technology and data roles in banking systems.
  • Read about HSBC's focus on Asia and international trade to show understanding of its business.
  • 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; HSBC interviewers usually ask follow-ups on your first answer.

Frequently asked questions

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

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

This practice set leans on Reports, Shiny and Production R (6), Statistics and Hypothesis Testing (5), Data Wrangling with dplyr and tidyr (4), Functions and Functional Programming (4). Revise those first, then practise explaining one or two of your own projects end to end, because most HSBC interviewers ask you to walk through real work.

Are these the exact questions asked at HSBC?

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

Where does HSBC hire R Programming professionals in India?

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

R Programming questions for similar companies