calculate index in r

To calculate an index in R, you can use a square bracket notation to subset a vector or a data frame. The index can be either a single value, a vector of values, or a logical vector.

Here are some basic examples:

  1. Subsetting a vector by a single index:
main.r
#Create a vector of numbers
numbers <- c(1, 2, 3, 4, 5)

#Extract the third element of the vector
numbers[3]
109 chars
6 lines

Output:

main.r
[1] 3
6 chars
2 lines
  1. Subsetting a vector by a vector of indices:
main.r
#Extract the second and fourth elements of the vector
numbers[c(2, 4)]
71 chars
3 lines

Output:

main.r
[1] 2 4
8 chars
2 lines
  1. Subsetting a vector by a logical vector:
main.r
#Create an index of TRUE and FALSE values based on a condition
index <- numbers > 3

#Extract the vector values where the index is TRUE
numbers[index]
151 chars
6 lines

Output:

main.r
[1] 4 5
8 chars
2 lines

These are just some basic examples of indexing. Depending on the data structure and the manipulation you need to perform, there are many other ways to use indexing in R.

gistlibby LogSnag