4

Basically, I want to take elements in vector k, but not in vector l, and append them to vector h. Here is my code using for loop:

k=c(1,2,3,5,8,9)
l=c(3,5,7,5,7,9,64)
h=c()

for (i in k) {
  if (!(i %in% l)) {
    print(i)
    append(h,i)
  }
}

After run the code, vector h does not change at all, but it should be c(1,2,8).

1
  • Append function does not work. But I have found simple working alternative: h = c(h,i) Nov 16, 2014 at 23:56

2 Answers 2

9

With append you need to assign the result

k=c(1,2,3,5,8,9)
l=c(3,5,7,5,7,9,64)
h=c()

for (i in k) {
  if (!(i %in% l)) {
    print(i)
    h<-append(h,i)
  }
}
1
  • Yeah the answer from @RichardScriven is totally better
    – keegan
    Nov 17, 2014 at 0:12
6

Use R's vectorization to your advantage. You could just do

k[!k %in% l]
# [1] 1 2 8
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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