Subsetting a dataset in R means selecting or excluding variables or observations. To select variables from a dataset you can use the bracket notation dt[,c("x","y")], where dt is the name of the dataset and “x” and “y” are the names of the variables. To exclude variables from a dataset, use the same notation but put a - sign before the column numbers, like dt[,c(-x,-y)].
Here is an example using the built-in iris dataset. First, let’s list its variables:
names(iris) "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
Suppose we want to select only “Sepal.Length” and “Sepal.Width” from the dataset:
dt <- iris[,c("Sepal.Length","Sepal.Width")]
names(dt)
"Sepal.Length" "Sepal.Width"
Now suppose we want to exclude only variables 2 and 3 (that is, the second and third columns):
dt <- iris[,c(-2,-3)] names(dt) "Sepal.Length" "Petal.Width" "Species"
Sometimes you need to select or exclude observations based on a certain condition. For this task the subset() function is used.
For this example we will create a new dataset:
Name <- c("John", "Tim", "Ami")
Sex <- c("men", "men", "women")
Age <- c(45, 53, 35)
dt <- data.frame(Name, Sex, Age)
Here is the dataset, called dt:
dt Name Sex Age John men 45 Tim men 53 Ami women 35
Now we want to keep only the men older than 40 years, and we will store the result in another dataset called dt2:
dt2 <- subset(dt, Age>40&Sex=="men") dt2 Name Sex Age John men 45 Tim men 53
As you can see, only the observations that meet both conditions are kept, so Ami is excluded from the new dataset.
The subset() function is broadly used in R programming whenever you work with datasets. Post a comment below if you have any questions about it.
Thank you Chris. I will update the post accordingly to your comment.