To split data in R into training and test sets, randomly select row indexes for the training set, then use the remaining rows for testing. For a basic 80/20 split, set a random seed, sample about 80% of the row numbers, and keep the other 20% aside until you evaluate the model.
Why split data into training and test sets?
A model can appear accurate simply because it has learned details of the data it saw during fitting. To estimate how it may perform on new observations, you need to evaluate it on data that was not used to train it. The training set is used to fit the model; the test set provides a separate check of its predictive performance.
This distinction matters for prediction, not just for machine learning competitions. For example, suppose a model predicts whether a customer will renew a subscription. If you train and score it on the same customer records, the score may reward memorization rather than the ability to generalize. Holding records back makes the evaluation more informative, provided the split reflects how the model will actually be used.
A test set is not a guarantee that a model will work well in every future setting. It is an estimate based on the observations available, and its reliability depends on the data, the split, and the evaluation metric. A small or unrepresentative test set can produce a misleading score.
Make a simple random split in base R
For a data frame named df, this base R example assigns roughly four-fifths of its rows to training and the rest to testing:
set.seed(123)
n <- nrow(df)
train_id <- sample(seq_len(n), size = floor(0.8 * n))
train <- df[train_id, , drop = FALSE]
test <- df[-train_id, , drop = FALSE]
set.seed(123) makes the random selection reproducible: rerunning the same code with the same data and R setup will select the same indexes. The particular seed value is not special; use a documented value so a colleague or a future run can recreate the split. seq_len(n) creates row numbers from 1 through the number of rows, and sample() selects the training indexes without replacement.
The minus sign in df[-train_id, ] means “all rows except these.” The commas separate row and column positions, so leaving the column position blank keeps every column. drop = FALSE helps preserve the result as a data frame even in edge cases where only one column is selected. This approach splits rows, not columns: predictors and the outcome remain together in each data frame.
Check that the split is sound
After splitting, check the number of rows, whether the sets overlap, and whether either set is empty. These quick checks can catch indexing errors before you fit a model:
nrow(train)
nrow(test)
length(intersect(train_id, setdiff(seq_len(n), train_id)))
The final expression should return zero because training indexes should not overlap with the indexes left for testing. You can also compare the result of nrow(train) + nrow(test) with nrow(df); the totals should match. With a very small data set, an 80/20 split may leave too few test cases for a stable evaluation, so consider cross-validation or collecting more observations rather than assuming a single score is definitive.
Make sure the data frame is in the intended state before splitting. Remove accidental duplicate rows if they would distort evaluation, and decide how to handle missing values as part of a training workflow. Do not silently delete rows based on information that would not be available at prediction time.
Use stratification for classification
A plain random split can leave a classification data set with very different class proportions in the two sets, especially when one class is rare. Stratification aims to preserve the distribution of the outcome across the split. For a categorical outcome, the caret package provides createDataPartition():
set.seed(123)
train_id <- caret::createDataPartition(
y = df$species,
p = 0.8,
list = FALSE
)
train <- df[train_id, , drop = FALSE]
test <- df[-train_id, , drop = FALSE]
Here, species is the classification outcome and p = 0.8 requests a training portion of about 80%. If needed, install the package once with install.packages("caret"). The returned indexes can be used just like those from the base R example. Compare class counts and proportions in both sets anyway; stratification does not create examples of a class that is absent, and very rare classes can still be difficult to represent adequately.
For a binary outcome, inspect the proportions rather than only the raw counts, since the sets may differ in size. A split that keeps the same class balance can make a comparison fairer, but it does not fix an unsuitable metric. When classes are imbalanced, accuracy alone can conceal poor detection of the minority class; consider measures such as sensitivity, specificity, precision, recall, or an appropriate area-under-curve metric.
Choose a split ratio and a validation strategy
An 80/20 split is a common starting point, not a universal rule. The right allocation depends on how much data you have, how complex the model is, and how precise the final performance estimate needs to be. A larger training set can help model fitting, while a larger test set can make evaluation less variable. With abundant data, a 70/15/15 division into training, validation, and test sets may be practical; with limited data, repeated cross-validation can use observations more efficiently.
Keep the roles of the sets clear:
- Training data: fit model parameters and learn patterns.
- Validation data: compare models, tune settings, or choose a decision threshold.
- Test data: provide a final evaluation after the modelling decisions are settled.
If you repeatedly check test-set results while changing features, algorithms, or tuning choices, you begin adapting decisions to that test set. It then acts more like validation data, and its score can become optimistic. Use cross-validation or a validation set for development decisions, then reserve the test set for the final check. If data is scarce, nested cross-validation can separate tuning from evaluation, though it takes more computation and care to implement.
Prevent leakage during preprocessing
Data leakage occurs when information from outside the training process influences fitting or evaluation in a way that would not be available when making real predictions. A common mistake is to standardize or impute the entire data set before splitting it. For example, calculating a mean from all rows lets the test observations influence the transformation used for training. Instead, estimate preprocessing values using training data, then apply those same learned values to validation and test data.
The same principle applies to feature selection, dimensionality reduction, target encoding, and choosing cutoffs. Put these operations inside a modelling workflow that fits them separately within each training fold when doing cross-validation. Otherwise, even if the outcome column is excluded from a particular calculation, information from held-out predictors can still make an evaluation less representative of future use.
Also check for leakage embedded in the columns themselves. A field recorded after the outcome occurs, an ID that indirectly encodes the answer, or a summary calculated using future records may make test performance look excellent while providing no valid prediction in practice. Ask of every predictor: would this value genuinely be known at the time the model is expected to predict?
When random splitting is not appropriate
Random row sampling assumes that observations can reasonably be treated as independent and drawn from the same population. That assumption is often wrong for time series, repeated measurements, households, patients, or multiple records belonging to one person. In those situations, a random split can put closely related or future information in training while a related record appears in testing, making performance look better than it will be in deployment.
- Time-ordered data: train on earlier observations and test on later ones. Do not randomly mix future records into the training set if the real task is forecasting.
- Repeated records per person or group: assign whole groups to one side of the split. This tests generalization to new groups rather than recognition of groups already seen.
- Spatial or clustered data: consider holding out locations or clusters when predictions must work in new places or clusters.
For forecasting, the test period should follow the training period in time; in some projects, rolling or expanding-window evaluation better reflects repeated future forecasts. For grouped observations, use a group-aware splitting method or construct the group assignment explicitly. The intended prediction question determines the split: predicting another measurement for a known patient differs from predicting outcomes for entirely new patients.
Common mistakes and practical alternatives
One frequent error is splitting after filtering or arranging data without realizing that the operation changed which observations are eligible. Another is using a seed but later changing the row order, which can change which records the sampled indexes refer to. Keep the split code close to the data preparation steps, and consider storing a stable record ID alongside the data so you can audit assignments.
Another mistake is selecting the best model based on repeated test-set comparisons and then reporting the same test score as an unbiased final estimate. A score is also not meaningful without context: state the metric, the size and nature of the test set, and any important class imbalance. When comparing models, use the same split so that differences are not simply caused by different test examples.
Useful alternatives include k-fold cross-validation, repeated cross-validation, and bootstrap evaluation, each with assumptions and trade-offs. In k-fold cross-validation, data is divided into folds; each fold is held out in turn while the others are used for fitting. This can reduce dependence on one random split, but preprocessing and tuning still need to happen within the appropriate folds. For time, group, or spatial data, ordinary random folds may still be inappropriate; use folds that respect the structure of the observations.
Frequently Asked Questions
How do I split data into 80% training and 20% testing in R?
Set a seed, sample floor(0.8 * nrow(df)) row indexes with sample(seq_len(nrow(df)), ...), and use those indexes for training. Use the negative indexes to make the test set, as shown above.
Does R have a built-in train-test split function?
Base R provides tools such as sample() for building a split, rather than one single general-purpose train-test function. Packages such as caret offer helpers, including stratified partitioning for common classification tasks.
Should I split before or after scaling the data?
Split first. Fit scaling values, such as a mean and standard deviation, using training data only, then apply those values to the test data. In cross-validation, repeat that fitting separately within each training fold.
Should I use the same random seed every time?
Use a fixed seed when you need a reproducible analysis or a fair comparison between models. Different seeds create different splits, so performance may vary. Do not choose a seed simply because it produces a preferred score.
Can I randomly split time-series data?
Usually not when the goal is to predict the future. Keep observations in chronological order, train on earlier data, and evaluate on later data so future information does not leak into model development.
A reliable rule of thumb
Start with a split that mirrors the real prediction task: random and possibly stratified for independent observations, chronological for forecasting, and group-aware when records are clustered. Keep the test set isolated from model decisions, perform preprocessing using training data only, and report what the split can and cannot establish. Those choices matter at least as much as whether the training share is 70%, 80%, or another familiar fraction.
Related
- Snowflake SPLIT_PART: Syntax, Examples & Tips
- Snowflake SPLIT_PART: Syntax, Examples, and Common Issues
- JavaScript split() Explained: Strings, Limits, and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Shortcut to the End of Data: Keys and LimitsIn Excel for Microsoft 365 on Windows, press Ctrl+Down Arrow to jump to the edge of the current…
- Excel Slicer Best Practices for Clear, Reliable ReportsFor reliable Excel slicers, start with a clean Excel Table or PivotTable, insert slicers only for fields people…
- How to Open Excel in a Browser and Edit Your FilesTo open Excel in a browser, go to microsoft365.com, sign in with a Microsoft account, and select Excel.…
- Excel Insert Row Shortcut: The Fastest Way to Add RowsIn Excel for Microsoft 365 on Windows, select the row where you want a new row, then press…
- How to Insert a Signature in Word on Windows and MacTo insert a signature in Word, add a picture of your handwritten signature, draw one with Word’s ink…
- Remove a Range Name in Excel: Step-by-Step GuideTo remove a range name in Excel for Microsoft 365 on Windows, open Formulas > Name Manager, select…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.