Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the flag if a column values are matching with those in another vector

Tags:

r

Suppose I've a data.frame as follows:

a <- data.frame(id=c(1,3,4,5,7,8,9,6,54,3,5,6,87,6))

And I have a vector temp as follows:

temp<-c(1,3,5,9)

Now, I want to create a new column flag on to my data.frame, where it should be 1 where id is in temp and 0 elsewhere. This is what I tried:

a$flag <- ifelse(a$id==temp, 1, 0)

and desired output should be (1,1,0,1,0,0,1,0,0,1,1,0,0,0).

But from my code above, flag is not getting updated properly. What am I missing here? Can/should I use %in%? If so, how?

Thank you for any help

like image 836
carl whyte Avatar asked Jul 01 '13 23:07

carl whyte


1 Answers

I think this is what you're looking for. There are a couple of problems in how you're making your data.frame:

a <- data.frame(id = c(1,3,4,5,7,8,9,6,54,3,5,6,87,6),
                flag = 0)

Then to update values of flag to 1 where id is in temp, you can index those values using [ and the logical test %in%, and assign them 1

a$flag[a$id %in% temp] <- 1

a
#    id flag
# 1   1    1
# 2   3    1
# 3   4    0
# 4   5    1
# 5   7    0
# 6   8    0
# 7   9    1
# 8   6    0
# 9  54    0
# 10  3    1
# 11  5    1
# 12  6    0
# 13 87    0
# 14  6    0
like image 176
alexwhan Avatar answered Oct 26 '22 07:10

alexwhan