MRF
MRF

Reputation: 377

Finding nearest number between two lists

I have a list of dataframes (df1) and another list of dataframes (df2) which hold values required to find the 'nearest value' in the first list.

df1<-list(d1=data.frame(y=1:10), d2=data.frame(y=3:20))
df2<-list(d3=data.frame(y=2),d4=data.frame(y=4))

Say I have this function:

df1[[1]]$y[which(abs(df1[[1]]$y-df2[[1]])== min(abs(df1[[1]]$y-df2[[1]])))]

This function works perfectly in finding the closest value of df2 value 1 in df1. What I can't achieve is getting to work with lapply as in something like:

lapply(df1, function(x){
  f<-x$y[which(abs(x$y-df2) == min(abs(x$y - df2)))]
})

I would like to return a dataframe with all f values which show the nearest number for each item in df1.

Thanks, M

Upvotes: 0

Views: 183

Answers (2)

bouncyball
bouncyball

Reputation: 10761

I assume you're trying to compare the first data.frames in df1 and df2 to each other, and the second data.frames in df1 and df2 to each other. It would also be useful to use the which.min function (check out help(which.min)).

edit

In response to your comment, you could use mapply instead:

> mapply(function(x,z) x$y[which.min(abs(x$y - z$y))], df1, df2)
d1 d2 
 2  4 

Upvotes: 1

Frank
Frank

Reputation: 66819

The OP's real problem is unclear, but I would probably do...

library(data.table)
DT1 = rbindlist(unname(df1), idcol=TRUE)
DT2 = rbindlist(unname(df2), idcol=TRUE)

DT1[DT2, on=c(".id","y"), roll="nearest"]

#    .id y
# 1:   1 2
# 2:   2 4

Upvotes: 1

Related Questions