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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With