Sjors Hendrikx
Sjors Hendrikx

Reputation: 19

extract value of Column B when value in column A has met with second data file in R

I have two data files. The first one is data file as followed

Cars   Engine  Tires 
Audi    77       55
Volvo   99       45
BMW     66       99
Opel    34       56

Second data file. The second data file changes often

Week27 
Car1      Car2
Audi      Volvo
Volvo     BMW
Opel      Audi

I want to extract the engine value or tire values from the corresponding cars and compare them to the other car. This changes weekly and the names of the cars as well. is there a code for this in R. Is there a function to do this quickly and only takes one value then out of df1 and use it corresponding where the same car is meant in df2

I want to use the values in a formula so something like this so no interaction of the Car name in this. How can I order it that it comes in order from the Week27 data file but uses the data from file 1

(77+99)/77 
(99+66)/66
(34+77)/34

Upvotes: 0

Views: 37

Answers (1)

Daniel O
Daniel O

Reputation: 4358

Based on your expected output you could use this:

apply(Week27,1,function(x) with(df1, (Engine[Cars==x[1]] + Engine[Cars==x[2]])/Engine[Cars==x[1]] ))

[1] 2.285714 1.666667 3.264706

Data:

df1 <- read.table(text='Cars   Engine  Tires 
Audi    77       55
Volvo   99       45
BMW     66       99
Opel    34       56',header=T)

Week27 <- read.table(text='Car1      Car2
Audi      Volvo
Volvo     BMW
Opel      Audi',header=T)

Upvotes: 1

Related Questions