Create dummies by matching characters

25 views Asked by At

I'm quite new with R. Suppose you have the following dataset:

df=data.frame(year=rep(2000:2004,4),country=c(rep("Argentina",5),rep("Canada",5),
rep("Mexico",5),rep("USA",5)))

Then, let's say I have the following character vectors:

latin_america=c("Argentina","Mexico")
north_america=c("USA","Canada")

By using these 2 vectors, I want to create 2 new columns, i.e., latin and north, where latin takes value 1 if country equals either Mexico or Argentina, and zero otherwise. North equals 1 if country equals either USA or Canada, and zero otherwise.

That's my attempt:

df$latin=0
df$north=0

df$latin[df$country==latin_america]=1
df$north[df$country==north_america]=1
0

There are 0 answers