Subset Function in R

Subset Function in R, returns subset of dataframe, vectors or matrices which meet the specified conditions.

Syntax of Subset Function in R:

subset(x, condition,select)
  • x – can be a matrix ,data frame or vector
  • condition- condition to be satisfied
  • select – columns to be selected

 

Example of Subset function in R:

Lets use mtcars data frame to demonstrate subset function in R.

# subset() function in R

newdata<-subset(mtcars,mpg>=30)	
newdata

Above code selects all data from mtcars data frame where mpg >=30 so the output will be

subset function in R 1

 

Example of Subset() function in R with select option:

# subset() function in R with select specific columns

newdata<-subset(mtcars,mpg>=30, select=c(mpg,cyl,gear))
newdata

Above code selects cars, mpg, cyl, gear from mtcars table where mpg >=30 so the output will be

subset function in R 2

 

Example of Subset() function in R with select option:

# subset() function in R

newdata<-subset(mtcars,mpg>=30, select=mpg:drat)	
newdata

Above code selects the columns in sequence order from mpg to drat from mtcars table where mpg >=30 so the output will be

subset function in R 3

 

previous subset function in R                                                                                                                next subset function in r