Reputation: 39
I feel this should be easy but at a loss, and hoping y'all can help. I have panel data, by id
with variables, here just v1
:
id v1
A 14
A 15
B 12
B 13
B 14
C 11
C 12
C 13
D 14
I would simply like to create a dummy variable indicating whether a value of v1
(say 12
) exists in the panel for id
. So something like:
id v1 v2
A 14 0
A 15 0
B 12 1
B 13 1
B 14 1
C 11 1
C 12 1
C 13 1
D 14 0
I feel this should be simple but can't figure out an easy one line solution.
Many many thanks!
Upvotes: 3
Views: 502
Reputation: 21621
Try
library(dplyr)
df %>% group_by(id) %>% mutate(v2 = as.numeric(any(v1 == 12)))
Or as per @akrun suggestion:
library(data.table)
setDT(df)[, v2 := any(v1 ==12)+0L, id]
Note: Adding 0L
to the logical values created by any()
will switch TRUE/FALSE
to 0
s and 1
s.
Another approach could be using ave
:
df$v2 <- with(df, ave(v1, id, FUN = function(x) any(x == 12)))
Which gives:
# id v1 v2
#1 A 14 0
#2 A 15 0
#3 B 12 1
#4 B 13 1
#5 B 14 1
#6 C 11 1
#7 C 12 1
#8 C 13 1
#9 D 14 0
Upvotes: 6