Monday, June 15, 2015

Two-Vector Dictionary in R using "match"


Something common in R is to have two vectors representing a key-value dictionary, for example:


  • Car name
  • Car price

Let's see an example:

We created two vectors using the dataset "car.test.frame" included in the package rpart. The first vector contains the name of the cars (key) and the second vector the list of prices (value). The function "match" is used to look for a couple of cars in the vector of names. If there is a match we get the index in the car_name vector (in our case, 37 and 43). Now we can use the indexes to work with the vector car_price or with the original data frame as a key-value dictionary.

Here is the code:

library(rpart)
str(car.test.frame)

# Get the name of the cars
car_name = row.names(car.test.frame)
car_price = car.test.frame$Price

# List of car's names
cars = c("Volvo 240 4", "Ford Taurus V6")
match(cars, car_name)

# Get the price of the car
car.test.frame[match(cars, car_name),]$Price

# or using the value-vector
car_price[match(cars, car_name)]

No comments:

Post a Comment