crumbly crumbly - 3 months ago 7
R Question

how to search for columns in data frames?

I have the following two data frames

u
and
v
. I am trying to create a resulting third data frame
w
using
u
and
v
such that each value in col
a
of df
u
is matched in cols in df
v
and then find the nth value from df
u
col
b
in df
v
of the matched column.

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
Comments