There is a data file with ID and columns y1, y2, …
> dat
id y1 y2 y3 y4 y5
1 1 2 4 2 3 4
2 2 4 1 1 4 4
3 3 2 3 1 3 1
4 4 0 1 2 4 4
5 5 3 3 2 1 4
6 6 4 1 3 1 4
7 7 2 4 4 4 0
8 8 2 5 0 2 5
9 9 2 2 3 3 1
10 10 0 3 4 4 3
There is a sample file with subset of IDs and week numbers.
> sam
id week
1 2 3
2 4 4
3 6 4
4 7 5
5 8 5
I want to assign a y value from dat to each sampled ID according the week number. This is the result I would like to achieve:
> res
id y
1 2 1
2 4 4
3 6 1
4 7 0
5 8 5
It is possible to achieve the result with some looping but I would like to avoid it if possible.
The structure of dat and sam.
dat <- structure(list(id = 1:10,
y1 = c(2, 4, 2, 0, 3, 4, 2, 2, 2, 0),
y2 = c(4, 1, 3, 1, 3, 1, 4, 5, 2, 3),
y3 = c(2, 1, 1, 2, 2, 3, 4, 0, 3, 4),
y4 = c(3, 4, 3, 4, 1, 1, 4, 2, 3, 4),
y5 = c(4, 4, 1, 4, 4, 4, 0, 5, 1, 3)),
.Names = c("id", "y1", "y2", "y3", "y4", "y5"),
row.names = c(NA, -10L),
class = "data.frame")
sam <- structure(list(id = c(2L, 4L, 6L, 7L, 8L),
week = c(3L, 4L, 4L, 5L, 5L)),
.Names = c("id", "week"),
row.names = c(NA, -5L),
class = "data.frame")
1 Answer