r - Merge function messes up the data order -
i have set of pairs of origin , destination points in df1
. add columns data a) attributes of orig
df2
. add attributes dest
column df3
. problem order of df1
gets rearranged , not intention. question how keep order of rows constant in final output without need add column @ beginning id, later on sort?
original table:
orig dest 1 b 2 b e 3 c 4 b c 5 b 6 c 7 e b orig = c("a","b","c","b","a","c","e") dest = c("b","e","a","c","b","a","b") df1 = data.frame(orig,dest) code <- c("a","b","c","d","e") name <- c("ams","bir","cas","das","ees") lat <- c(4,6,7,3,2) long <- c(13,45,63,43,23) df2 <- data.frame(code,name,lat,long) df3 <- data.frame(code,name,lat,long) colnames(df2) <- c("orig","name","lat","long") colnames(df3) <- c("dest","name","lat","long") result1 <- merge(df1,df2,by = c("orig"), sort=false) # tried without sort result2 <- merge(result1,df3,by = c("dest"), sort=false)
my current outcome
dest orig name.x lat.x long.x name.y lat.y long.y 1 b ams 4 13 bir 6 45 2 b ams 4 13 bir 6 45 3 b e ees 2 23 bir 6 45 4 e b bir 6 45 ees 2 23 5 c b bir 6 45 cas 7 63 6 c cas 7 63 ams 4 13 7 c cas 7 63 ams 4 13
desired outcome:
orig dest name.x lat.x long.x name.y lat.y long.y 1 b ams 4 13 bir 6 45 2 b e bir 6 45 ees 2 23 3 c cas 7 63 ams 4 13 4 b c bir 6 45 cas 7 63 5 b ams 4 13 bir 6 45 6 c cas 7 63 ams 4 13 7 e b ees 2 23 bir 6 45
so depending on if want attributes match orig or dest, change up, can sort attributes df2
either orig or dest:
df2[charmatch(orig,code),]
and add in dest/orig column df1
Comments
Post a Comment