Mandar has graciously written this code for me from this Q/A in r, how to assess the two vectors based on other vectors
names(df) <- c("a","b","c","d")
df_backup <- df
df$newcol <- NA
used <- c()
for (i in seq(1,length(df$a),1)){
print("######## Separator ########")
print(paste("searching right match that fits criteria for ",df$a[i],"in column 'a'",sep=""))
valuea <- df[i,1]
orderx <- order(abs(df$b-valuea))
index=1
while (is.na(df$newcol[i])) {
j=orderx[index]
if (df$b[j] %in% used){
print(paste("passing ",df$b[j], "as it has already been used",sep=""))
index=index+1
next
} else {
indexb <- j
valueb <- df$b[indexb]
print(paste("trying ",valueb,sep=""))
if (df$c[i] != df$d[indexb]) {
df$newcol[i] <- df$b[indexb]
print(paste("using ",valueb,sep=""))
used <- c(used,df$b[indexb])
} else {
df$newcol[i] <- NA
print(paste("cant use ",valueb,"as the column c (related to index in a) and d (related to index in b) values are matching",sep=""))
}
index=index+1
}
}
}
this is what my data look like
a b c d
12.9722051 297.9117268 1 1
69.64816997 298.1908749 2 2
318.8794557 169.0386352 3 3
326.1762208 169.3201391 4 4
137.5400592 336.6595313 5 5
358.0600171 94.70890334 6 6
258.9282428 94.77530919 7 7
98.57513917 290.1983195 8 8
98.46303072 290.4078981 9 9
17.2276417 344.383796 10 10
316.6442074 148.786547 11 11
310.7370168 153.3287735 12 12
237.3270752 107.8397117 13 13
250.6538555 108.0570571 14 14
337.0954288 180.6311769 15 15
137.0336521 1.0294907 16 16
301.2277242 185.2062845 17 17
332.935301 185.9792236 18 18
340.841266 220.4043846 19 19
the values in column a and b are compass bearings. currently, the formula looks at a value in column a and compares it to all values in column b and finds the closest one. but what i realized i need it to do is look at a value in column b, but not only find the nearest value based on absolute difference, but also take into account that it is a compass bearing. for example: for the value in column a of 358.0600171 the current formula would return a value from column b of 344.383796, which is ~14 degrees away from 358.060171; however, the actual closest bearing value from column b should be 1.0294907 which is only 3 degrees away from 358.0600171. i would like to incorporate a function that that accounts for this compass bearing issue into the current formula: which does all my other needed evaluation, filtering, and column creation.
There a similar query here(Finding the closest difference between 2 degrees of a compass - Javascript), but I need assistance on whether the function will work in R, and how to incorporate it into the existing formula.