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
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
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))]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.