OneBite.Dev - Coding blog in a bite size

extract a sub-array from an array in R

Code snippet on how to extract a sub-array from an array in R

  my_array <- c(1,2,3,4,5,6,7,8,9)
  my_subarray <- my_array[3:7]

This code uses R’s indexing to extract a sub-array from an existing array. The first line creates an array with 9 elements (1 to 9) named ‘my_array’. The second line extracts a sub-array with the elements located between index 3 and 7 (3 to 7 inclusive) and assigns it to ‘my_subarray’. This line utilizes the square bracket syntax of R to extract the sub-array, with 3 and 7 indicating the starting and ending indices (inclusive) of the sub-array. The result is that ‘my_subarray’ contains elements 3, 4, 5, 6 and 7 from ‘my_array’.

r