crumbly - 5 months ago 17

R Question

I have the following two data frames

`u`

`v`

`w`

`u`

`v`

`a`

`u`

`v`

`u`

`b`

`v`

`u<-data.frame(a=c("v2","x2","x2"),b=c(2,3,4))`

v<-data.frame(No=c(1,2,3,4,5),v1=c(2,9,3,1,7),v2=c(9,10,8,8,7),w1=c(5,7,9,4,3),

w2=c(4,6,1,3,2),x1=c(9,6,2,7,4),x2=c(4,4,4,2,7))

Resulting data frame

`w <-data.frame(a=c("v2","x2","x2"),b=c(2,3,4),c=c(10,4,2))`

Answer

We can `match`

the 'a' column in 'u' with the `names`

of 'v' to get the `column`

index, `cbind`

with 'b' column (row index), extract the values from 'v', and create the 'c' column with `transform`

and assign it to a new dataset object ('w').

```
w <- transform(u, c= v[cbind(b, match(as.character(a), names(v)))])
w
# a b c
#1 v2 2 10
#2 x2 3 4
#3 x2 4 2
```