Stackbeans
Stackbeans

Reputation: 279

Merge double integers with different decimal places

I want to merge two datasets based on their double integers, however one of the falls short 2 decimal places but I would like to merge them regardless if all units from the short match its relative length to the longer. The final integer can be of the longer or shorter one.

Example with expectation (xy):

x = c(0.456, 0.797, 0.978, 0.897, 0.567)
x1 = c(0.45698, 0.79786, 0.97895, 0.75869, 0.56049)

x           x1
0.456  0.45698
0.797  0.79786
0.978  0.97895

# or if they match then replace with longer integers

I have tried merge but it duplicates:

> xx1<-merge(x, x1)
> unique(xx1)
      x      x1
1 0.456 0.45698
2 0.797 0.45698
3 0.978 0.45698
4 0.456 0.79786
5 0.797 0.79786
6 0.978 0.79786
7 0.456 0.97895
8 0.797 0.97895
9 0.978 0.97895

Upvotes: 2

Views: 200

Answers (1)

GKi
GKi

Reputation: 39667

You can use pmatch:

i <- pmatch(x, x1)
j <- !is.na(i)
cbind(x=x[j], x1=x1[i[j]])
#         x      x1
#[1,] 0.456 0.45698
#[2,] 0.797 0.79786
#[3,] 0.978 0.97895

Upvotes: 1

Related Questions