0

If I have 2 vectors of length 7 and 4 respectively (in R),

vec1 <- c(1.0, 1.0, 2.0, 3.0, 4.0, 4.0, 5.0)


vec2 <- c(1.0, 2.0, 4.0, 5.0)

I want to output a vector that shows the elements added to vec2 in order to create vec1

output <- c(1.0, 3.0, 4.0)
3
  • 1
    These are floating points. So you won't get exact match
    – akrun
    Jul 5, 2020 at 18:40
  • -9.0, -8.0, -4.0, 2.0, and -6.5 are in both vectors, so they won't appear in the output Jul 5, 2020 at 18:43
  • You need to define what you mean by "additional elements"? Do you mean "elements of vec1 with index 36 to 42"? No, because -9.0 is not the 36th lements of vec1. Do you mean "values in vec1 that are not values in vec2? No, because -9.0 appears in both vec1 and vec2 and in your desired output. So I don't know how you define "additional elements".
    – Limey
    Jul 5, 2020 at 18:44

1 Answer 1

1

setdiff seems to be working just fine:

> sort(unique(vec1))
 [1] -14.5 -13.5 -10.5 -10.0  -9.0  -8.5  -8.0  -7.5  -6.5  -5.5  -5.0  -4.5  -4.0  -3.5  -2.5   1.5   2.0
[18]   2.5   5.0   5.5   6.5   8.0   8.5  10.5
> sort(unique(vec2))
 [1] -14.5 -13.5 -10.5 -10.0  -9.0  -8.5  -8.0  -7.5  -6.5  -5.5  -5.0  -4.5  -4.0  -3.5  -2.5   2.0   2.5
[18]   5.5   6.5   8.0   8.5  10.5

Only 1.5 and 5.0 are in vec1 and not in vec2

2
  • 1
    @Akrun, I just wanted to make the OP clear that what setdiff 'only' outputs is correct. We can probably close the question
    – Waldi
    Jul 5, 2020 at 19:08
  • Please let me know if the edit helps make the question a little more clear
    – tpeccorini
    Jul 6, 2020 at 16:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.