Problem:
Access the elements in a Data Frame
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:
0 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:
3. Sorting Data in a Data Frame in R
Happy Coding!