Indexing Basics

We use square brackets to access specific elements of a vector. For the vector codes we defined above, we can access the second element using:

codes[2]
#> canada 
#>    124

You can get more than one entry by using a multi-entry vector as an index:

codes[c(1,3)]
#> italy egypt 
#>   380   818

The sequences defined above are particularly useful if we want to access, say, the first two elements:

codes[1:2]
#>  italy canada 
#>    380    124

If the elements have names, we can also access the entries using these names. Below are two examples.

codes["canada"]
#> canada 
#>    124
codes[c("egypt","italy")]
#> egypt italy 
#>   818   380

Instruction

  • Click Run button to see the usage of indexing.
# Make codes vector with names of country. codes <- c(380, 124, 818) country <- c("italy","canada","egypt") names(codes) <- country # You can access the second value in codes vector codes[2] # When you use two or more indexes, please use c function. codes[c(1,3)] # You can use : symbol for multiple indexing. codes[1:2] # You can use the assgined name to access the value. codes["canada"] # You can use the two or more assgined name to access the value. codes[c("egypt","italy")]

Previous: 1-15 | which(): Find an index under condition

Next: 2-1 | Programming basics

Back to Main