minhsphuc12
minhsphuc12

Reputation: 68

Append values to vector by for loop not working

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).

Upvotes: 4

Views: 10767

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

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

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

Upvotes: 6

keegan
keegan

Reputation: 2992

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)
  }
}

Upvotes: 9

Related Questions