I have two data frame

```
A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1

```

and B

```
 Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914

```

I would like to calculate the minimum difference between each value of `A$X1` and all values of `B$Longitude`, based on group-index `Year_month`, and report in a new column of `A` the value of `B$CHL`

Let's say when `A$X1`, minus each value of `B$longitude`, values for values, for the same `Year_month` group is the minimum difference, I put in a column `A$res` the values of `B$CHL`
Example, for the first row of df A: 

```
A[1,1]-B[1,1]
A[1,1]-B[2,1]   
A[1,1]-B[3,1] ---> this is the minimum difference

```

in the column `A$res` I put the result 12.58 (value of `B[3,3]`), and so on for each row of `A$X1`

```
I tried this code: 
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))

```

But I have the error: 

```
Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { : 
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used

```

Any idea???

P.S: 

```
sapply(A,class)
        X1 Year_month 
  "factor"   "factor" 

sapply(B,class)
 Longitude Year_month        CHL 
  "factor"   "factor"  "numeric"

```