Vector Slicing and Indexing
Part of the Fundamentals section of Coddy's R journey — lesson 67 of 78.
You've learned how to access single elements and iterate through vectors. Now let's explore how to extract multiple elements at once using slicing. This technique lets you grab a subset of a vector in a single operation.
To extract multiple elements, pass a vector of indices inside the square brackets:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[c(1, 3, 5)])Output:
[1] 10 30 50You can also use the colon operator to select a range of consecutive elements:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[2:4])Output:
[1] 20 30 40Negative indices are powerful in R. They exclude elements instead of selecting them:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[-2])Output:
[1] 10 30 40 50You can exclude multiple elements by passing a vector of negative indices:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[-c(1, 5)])Output:
[1] 20 30 40Remember: you cannot mix positive and negative indices in the same selection. R will throw an error if you try numbers[c(1, -2)].
Challenge
EasyYou will receive two lines of input:
- A comma-separated list of numbers (e.g.,
100,200,300,400,500,600,700) - Two indices separated by a comma representing a range to exclude (e.g.,
2,5)
Perform the following operations:
- Create a numeric vector from the comma-separated numbers
- Print elements at positions 1, 3, and 5 using a vector of indices
- Print elements from position 2 to position 4 using the colon operator
- Print the vector with the element at the first given index excluded (using negative indexing)
- Print the vector with elements from the first index to the second index excluded (using negative indexing with a range)
For example, if the inputs are:
10,20,30,40,50,60,70
3,5The output should be:
[1] 10 30 50
[1] 20 30 40
[1] 10 20 40 50 60 70
[1] 10 20 60 70Explanation:
- Elements at positions 1, 3, 5 are: 10, 30, 50
- Elements from position 2 to 4 are: 20, 30, 40
- Excluding position 3 gives: 10, 20, 40, 50, 60, 70
- Excluding positions 3 through 5 gives: 10, 20, 60, 70
Cheat sheet
To extract multiple elements from a vector, pass a vector of indices inside square brackets:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[c(1, 3, 5)]) # [1] 10 30 50Use the colon operator to select a range of consecutive elements:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[2:4]) # [1] 20 30 40Negative indices exclude elements instead of selecting them:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[-2]) # [1] 10 30 40 50Exclude multiple elements by passing a vector of negative indices:
numbers <- c(10, 20, 30, 40, 50)
print(numbers[-c(1, 5)]) # [1] 20 30 40Important: You cannot mix positive and negative indices in the same selection.
Try it yourself
# Read input
con <- file("stdin", "r")
numbers_input <- suppressWarnings(readLines(con, n = 1))
indices_input <- suppressWarnings(readLines(con, n = 1))
close(con)
# Parse the comma-separated numbers into a numeric vector
numbers <- as.numeric(strsplit(numbers_input, ",")[[1]])
# Parse the two indices
indices <- as.numeric(strsplit(indices_input, ",")[[1]])
idx1 <- indices[1]
idx2 <- indices[2]
# TODO: Write your code below
# 1. Print elements at positions 1, 3, and 5 using a vector of indices
# 2. Print elements from position 2 to position 4 using the colon operator
# 3. Print the vector with the element at idx1 excluded (negative indexing)
# 4. Print the vector with elements from idx1 to idx2 excluded (negative indexing with range)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 27Bill Split Calculator
Welcome MessageGetting User Input13Vectors Advanced
Vector Slicing and IndexingLogical IndexingVector Arithmetic & RecyclingThe %in% Operator2Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values