Named Vectors in R
Named Vectors in R
A named vector is a vector in which each element is assigned a name. The names act as labels for the elements, making the vector easier to understand and allowing values to be accessed by name instead of only by position.
Syntax
vector_name <- c(Name1 = value1, Name2 = value2, Name3 = value3)
Example 1: Creating a Named Vector
marks <- c(English = 85, Maths = 92, Science = 88) print(marks)
Output
English Maths Science 85 92 88
Accessing Elements
By Name
marks["Maths"]
Output
Maths 92
By Position
marks[2]
Output
Maths 92
Displaying Names
Use the names() function to retrieve the names of the vector elements.
names(marks)
Output
[1] "English" "Maths" "Science"
Modifying an Element
marks["Science"] <- 95 print(marks)
Output
English Maths Science 85 92 95
Example 2: Returning Multiple Values from a Function
Named vectors are commonly used to return multiple values from a function.
statistics <- function(v) { return(c( Sum = sum(v), Average = mean(v), Maximum = max(v), Minimum = min(v) )) } v <- c(10, 20, 30, 40) result <- statistics(v) print(result)
Output
Sum Average Maximum Minimum 100.0 25.0 40.0 10.0
Accessing individual values:
result["Sum"] result["Average"] result["Maximum"]
Advantages of Named Vectors
- Makes the output more readable by assigning meaningful labels.
- Allows elements to be accessed using names instead of numeric indices.
- Reduces programming errors caused by incorrect indexing.
- Useful for returning multiple related values from a function.
- Simplifies the interpretation of statistical and computational results.
Limitations
- All elements of a vector must have the same data type.
- A named vector cannot store mixed data types (e.g., numeric values and character strings together). In such cases, a list should be used.
Applications of Named Vectors
- Returning multiple numerical results from a function.
- Storing subject-wise marks of a student.
- Representing monthly sales figures.
- Storing statistical measures such as mean, median, and standard deviation.
- Holding configuration parameters with descriptive names.
Summary
A named vector is a vector whose elements are associated with descriptive names. It improves the readability of programs, enables easy access to elements using names, and is particularly useful when returning multiple values of the same data type from a function. For mixed data types, however, a list is the preferred data structure.
Comments
Post a Comment