0
0
R Programmingprogramming~5 mins

Row and column indexing in R Programming

Choose your learning style9 modes available
Introduction

Row and column indexing helps you pick specific parts of a table or matrix to look at or change.

You want to see just one row of data from a table.
You need to get a specific column from a dataset.
You want to change a value in a certain row and column.
You want to select multiple rows or columns to analyze.
You want to filter data based on row or column positions.
Syntax
R Programming
data[row_index, column_index]

Use numbers to pick rows and columns by position.

Leave row or column blank to select all in that dimension, like data[, 2] for all rows in column 2.

Examples
Selects the first row, all columns.
R Programming
data[1, ]
Selects all rows, third column.
R Programming
data[, 3]
Selects the value at row 2, column 4.
R Programming
data[2, 4]
Selects rows 1 to 3 and columns 2 and 4.
R Programming
data[1:3, c(2,4)]
Sample Program

This program creates a 3x4 matrix with numbers 1 to 12. Then it prints:

  • The first row (all columns)
  • The second column (all rows)
  • The value at row 2, column 3
  • Rows 1 and 2, columns 1 and 4
R Programming
data <- matrix(1:12, nrow=3, ncol=4)
print(data[1, ])
print(data[, 2])
print(data[2, 3])
print(data[1:2, c(1,4)])
OutputSuccess
Important Notes

Indexing starts at 1 in R, not 0 like some other languages.

You can use negative numbers to exclude rows or columns, e.g., data[-1, ] excludes the first row.

Use names instead of numbers if your data has row or column names, like data['row1', 'col2'].

Summary

Row and column indexing lets you pick parts of data by position.

Use data[row, column] with numbers or names.

Leaving row or column blank selects all in that dimension.