Accessing Data Frame Elements in R

Problem:
Access the elements in a Data Frame
Solution:
We need to select the elements from a data frame with the help of square brackets[], same as in Vectors or Matrices.By using a comma, we can indicate what to select from the rows and the columns respectively. 
For example:

  • df[1, 2] -> selects the value at the first row and selects an element of the second column in the data frame df.
  • df[1:3, 2:4] -> selects rows 1, 2, 3 and columns 2, 3, 4 in the data frame df.
  • df[, 2:4] -> selects all elements from the row and columns 2,3,4 in the data frame df


Above is the example Data Frame mtcars.

1. Select ‘mpg’ and ‘cyl’ column  value for all cars:

2. Now, select all the elements from the first two rows

3. Fetch ‘carb’ column value for all cars

4. Remove the first column values for all cars

Read more about Data frames in R from below:

1.Creating a Data Frame in R

2. Export Data Into CSV in R

3. Sorting Data in a Data Frame in R

Happy Coding!

0

Leave a Reply

Your email address will not be published. Required fields are marked *