How to Create and Assign Named Vectors in R

You use the assignment operator (<-) to assign names to vectors in much the same way that you assign values to character vectors.

Imagine you want to create a named vector with the number of days in each month. First, create a numeric vector containing the number of days in each month. Then use the built-in dataset month.name for the month names, as follows:

> month.days <- c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
> names(month.days) <- month.name
> month.days
 January February   March   April
    31    28    31    30
   May   June   July  August
    31    30    31    31
September  October November December
    30    31    30    31

Now you can use this vector to find the names of the months with 31 days:

> names(month.days[month.days==31])
[1] "January" "March"  "May"
[4] "July"   "August"  "October"
[7] "December"

This technique works because you subset month.days to return only those values for which month.days equals 31, and then you retrieve the names of the resulting vector.

The double equal sign (==) indicates a test for equality. Make sure not to use the single equal sign (=) for equality testing. Not only will a single equal sign not work, but it can have strange side effects because R interprets a single equal sign as an assignment. In other words, the operator = in many cases is the same as <-.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.