r - how to search for columns in data frames? -
i have following 2 data frames u , v. trying create resulting third data frame w using u , v such each value in col a of df u matched in cols in df v , find nth value df u col b in df v of 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))
we can match 'a' column in 'u' names of 'v' column index, cbind 'b' column (row index), extract values 'v', , create 'c' column transform , assign new dataset object ('w').
w <- transform(u, c= v[cbind(b, match(as.character(a), names(v)))]) w # b c #1 v2 2 10 #2 x2 3 4 #3 x2 4 2
Comments
Post a Comment