Related Articles

Related Articles

Subsetting in R Programming
  • Last Updated : 28 Jul, 2020

In R programming, subsetting allows the user to access elements from an object. It takes out a portion from the object based on the condition provided. There are 4 ways of subsetting in R programming. Each of the methods depends on the usability of the user and the type of the object. For example, if there is a data frame with many columns such as states, country, and population and suppose the user wants to extract states from it, then subsetting is used to do this operation. In this article, let us discuss the implementation of different types of subsetting in R programming.

Subsetting Using [ ] Operator

Using ‘[ ]’ operator, elements of vectors and observations from data frames can be accessed. To neglect some indexes, ‘-‘ is used to access all other indexes of vector or data frame.
Example 1:
In this example, let us create a vector and perform subsetting using the [ ] operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Create vector
x <- 1:15
  
# Print vector
cat("Original vector: ", x, "\n")
  
# Subsetting vector
cat("First 5 values of vector: ", x[1:5], "\n")
  
cat("Without values present at index 1, 2 and 3: "
                              x[-c(1, 2, 3)], "\n")

chevron_right


Output:

Original vector:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
First 5 values of vector:  1 2 3 4 5
Without values present at index 1, 2 and 3:  4 5 6 7 8 9 10 11 12 13 14 15

Example 2:
In this example, let us use mtcars data frame present in R base package for subsetting.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Dataset
cat("Original dataset: \n")
print(mtcars)
  
# Subsetting data frame
cat("HP values of all cars:\n")
print(mtcars['hp'])
  
# First 10 cars
cat("Without mpg and cyl column:\n")
print(mtcars[1:10, -c(1, 2)])

chevron_right


Output:



Original dataset:
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2

HP values of all cars:
                     hp
Mazda RX4           110
Mazda RX4 Wag       110
Datsun 710           93
Hornet 4 Drive      110
Hornet Sportabout   175
Valiant             105
Duster 360          245
Merc 240D            62
Merc 230             95
Merc 280            123
Merc 280C           123
Merc 450SE          180
Merc 450SL          180
Merc 450SLC         180
Cadillac Fleetwood  205
Lincoln Continental 215
Chrysler Imperial   230
Fiat 128             66
Honda Civic          52
Toyota Corolla       65
Toyota Corona        97
Dodge Challenger    150
AMC Javelin         150
Camaro Z28          245
Pontiac Firebird    175
Fiat X1-9            66
Porsche 914-2        91
Lotus Europa        113
Ford Pantera L      264
Ferrari Dino        175
Maserati Bora       335
Volvo 142E          109

Without mpg and cyl column:
                   disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          167.6 123 3.92 3.440 18.30  1  0    4    4

Subsetting Using [[ ]] Operator

[[ ]] operator is used for subsetting of list objects. This operator is same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 elements in a single command.
Example 1:
In this example, let us create a list and select the elements using [[]] operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Create list
ls <- list(a = 1, b = 2, c = 10, d = 20)
  
# Print list
cat("Original List: \n")
print(ls)
  
# Select first element of list
cat("First element of list: ", ls[[1]], "\n")

chevron_right


Output:

Original List:
$a
[1] 1

$b
[1] 2

$c
[1] 10

$d
[1] 20

First element of list:  1 

Example 2:
In this example, let us create a list and recursively select elements using c() function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Create list
z <- list(a = list(x = 1, y = "GFG"), b = 1:10)
  
# Print list
cat("Original list:\n")
print(z)
  
# Print GFG using c() function
cat("Using c() function:\n")
print(z[[c(1, 2)]])
  
# Print GFG using only [[]] operator
cat("Using [[]] operator:\n")
print(z[[1]][[2]])

chevron_right


Output:

Original list:
$a
$a$x
[1] 1

$a$y
[1] "GFG"


$b
 [1]  1  2  3  4  5  6  7  8  9 10

Using c() function:
[1] "GFG"

Using [[]] operator:
[1] "GFG"

Subsetting Using $ Operator

$ operator can be used for lists and data frames in R. Unlike [ ] operator, it selects only a single observation at a time. It can be used to access an element in named list or a column in data frame. $ operator is only applicable for recursive objects or list-like objects.
Example 1:
In this example, let us create a named list and access the elements using $ operator

filter_none

edit
close

play_arrow

link
brightness_4
code

# Create list
ls <- list(a = 1, b = 2, c = "Hello", d = "GFG")
  
# Print list
cat("Original list:\n")
print(ls)
  
# Print "GFG" using $ operator
cat("Using $ operator:\n")
print(ls$d)

chevron_right


Output:

Original list:
$a
[1] 1

$b
[1] 2

$c
[1] "Hello"

$d
[1] "GFG"

Using $ operator:
[1] "GFG"

Example 2:
In this example, let us use the mtcars dataframe and select a particular column using $ operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Dataset
cat("Original data frame:\n")
print(mtcars)
  
# Access hp column
cat("Using $ operator:\n")
print(mtcars$hp)

chevron_right


Output:



Original data frame:
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2

Using $ operator:
[1] 110 110  93 110 175 105 245  62  95 123 123 180 180 180 205 215 230  66  52
[20]  65  97 150 150 245 175  66  91 113 264 175 335 109

Subsetting Using subset() Function

subset() function in R programming is used to create a subset of vectors, matrices or data frames based on the conditions provided in the parameters.

Syntax: subset(x, subset, select)

Parameters:
x: indicates the object
subset: indicates the logical expression on the basis of which subsetting has to be done
select: indicates columns to select

Example 1:
In this example, let us use airquality data frame present in R base package and select Month where Temp < 65.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Subsetting
airq <- subset(airquality, Temp < 65, 
                  select = c(Month))
  
# Print subset
print(airq)

chevron_right


Output:

    Month
4       5
5       5
8       5
9       5
15      5
16      5
18      5
20      5
21      5
23      5
24      5
25      5
26      5
27      5
144     9
148     9

Example 2:
In this example, let us use mtcars data frame present in R base package and selects the car with 5 gears and hp > 200.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Subsetting
mtc <- subset(mtcars, gear == 5 & hp > 200, 
                      select = c(gear, hp))
  
# Print subset
print(mtc)

chevron_right


Output:

               gear  hp
Ford Pantera L    5 264
Maserati Bora     5 335
My Personal Notes arrow_drop_up
Recommended Articles
Page :