I have two data frames as follows :
df1 <- t(data.frame(seq(1,6,by=1),seq(6,1,by=-1)))
colnames(df1) <- c(\"A\",\"B\",\"C\",\"D\",\"E\",\"F)
ro
We can use merge
with melt
. The melt
returns a three column data.frame
, merge
it with the second dataset to create the new column
library(reshape2)
merge(df2, melt(df1), by.x = c("Vector1", "Vector2"), by.y = c("Var2", "Var1"))
Or a base R
option would be to get the numeric index with match
after paste
ing the 'df2' rowwise (do.call(paste
) and get the paste
d column names and row names of 'df1' using outer
. Using the numeric index, we get the values in 'df1' to create the 'Newcol'
df2$Newcol <- df1[match(do.call(paste, df2),
t(outer(colnames(df1), rownames(df1), FUN = paste)))]
df2$Newcol
#[1] 1 5 3 3 5 1 1 5 3 3 5 1