Indexing Vector Elements
You can access elements of a vector by their position (numeric index) or by their assigned names.
In R, indices start at 1.
Accessing Single Element
You can extract one element at a time either by its position in the vector or by its assigned name.
Example
1234567grades <- c(80, 75, 95, 100) names(grades) <- c('Math', 'Physics', 'English', 'Literature') # First grade grades[1] # Grade for Literature grades['Literature']
Accessing Multiple Elements
You can also select several elements at once by passing a vector of indices or names.
Example
1234567grades <- c(80, 75, 95, 100) names(grades) <- c('Math', 'Physics', 'English', 'Literature') # Second and third grades grades[c(2,3)] # Grades for Math and Physics grades[c('Math', 'Physics')]
Swipe to start coding
You have a vector named prices with each price assigned to a corresponding item name. Your task is to:
- Retrieve the price of
'Armchair'using its name rather than its index. - Retrieve the prices for both the
'Dining table'and'Dining chair'using their indices.
Løsning
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Fantastisk!
Completion rate forbedret til 2.27
Indexing Vector Elements
Sveip for å vise menyen
You can access elements of a vector by their position (numeric index) or by their assigned names.
In R, indices start at 1.
Accessing Single Element
You can extract one element at a time either by its position in the vector or by its assigned name.
Example
1234567grades <- c(80, 75, 95, 100) names(grades) <- c('Math', 'Physics', 'English', 'Literature') # First grade grades[1] # Grade for Literature grades['Literature']
Accessing Multiple Elements
You can also select several elements at once by passing a vector of indices or names.
Example
1234567grades <- c(80, 75, 95, 100) names(grades) <- c('Math', 'Physics', 'English', 'Literature') # Second and third grades grades[c(2,3)] # Grades for Math and Physics grades[c('Math', 'Physics')]
Swipe to start coding
You have a vector named prices with each price assigned to a corresponding item name. Your task is to:
- Retrieve the price of
'Armchair'using its name rather than its index. - Retrieve the prices for both the
'Dining table'and'Dining chair'using their indices.
Løsning
Takk for tilbakemeldingene dine!
single