Math
Math

Reputation: 1294

Matching all pairs of 2 vectors to third column

I have this data.frame :

x1=c(1,2,3,4,5)
values=c(1.5,2.2,1.1,2.3,1.1)
d=data.frame(x1,values)

I devided x1 to

x=c(1,2)
y=c(3,4,5)

and then I calculate all pairs using expand.grid

e=expand.grid(x=x,y=y)

> e
  x y
  1 3
  2 3
  1 4
  2 4
  1 5
  2 5

My question is how to calculate a third column that gives values(x)/values(y) ?? Like :

  x y values_1
  1 3 1.5/1.1
  2 3 2.2/1.1
  1 4 1.5/2.3
  2 4 2.2/2.3
  1 5 1.5/1.1
  2 5 2.2/1.1

Thank you for help.

Upvotes: 2

Views: 41

Answers (1)

Frank
Frank

Reputation: 66819

You want to use square brackets:

e$newcol <- with(e,values[x]/values[y])

or similarly

e$newcol <- values[e$x]/values[e$y]

which makes e:

  x y    newcol
1 1 3 1.3636364
2 2 3 2.0000000
3 1 4 0.6521739
4 2 4 0.9565217
5 1 5 1.3636364
6 2 5 2.0000000

To find out more, type help.start(), navigate to the "Introduction to R" document and its section on "Index vectors; selecting and modifying subsets of a data set".

Upvotes: 4

Related Questions