Question

I would like to merge two dataframes (dat1 and dat2) comparing the column and row strings.

dat1:

NE001  NE002  NE003
-1.2     3      2
 2     -1.2     3
 3      2     -1.5

dat2:

NE_id   value
NE001    2
NE002   -0.4
NE003    3

My expected output

NE001  NE001  NE002   NE002   NE003  NE003
-1.2     2      3     -0.4      2     3
 2       2    -1.2    -0.4      3     3
 3       2      2     -0.4    -1.5    3
Was it helpful?

Solution

Hopefully this isn't an over-simplification of your actual problem, but by the looks of it, cbind might be an option for you to consider:

out <- cbind(dat1, 
             setNames(data.frame(t(replicate(nrow(dat1), dat2$value))), 
                      dat2$NE_id))
out[, order(names(out))]
#   NE001 NE001.1 NE002 NE002.1 NE003 NE003.1
# 1  -1.2       2   3.0    -0.4   2.0       3
# 2   2.0       2  -1.2    -0.4   3.0       3
# 3   3.0       2   2.0    -0.4  -1.5       3

OTHER TIPS

This may not be very elegant but it should work :

 for(i in 1:dim(dat1)[1])
{
    dat2bis[,i]<-dat2bis[,1]
}

dat3<-cbind(dat1,dat2bis)
dat3<-dat3[,order(colnames(dat3))]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top