Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating dummy variables in R where element in data frame 2 is in data frame 1

I have a main data frame with a column for year of event A occurring. I have two separate data frames with year of events B and year of event C occurring.

Sample dataframe:

year_eventA <- c(1995,1996,1997,1998,1999)
year_eventB <- c(1997,1999)
year_eventC <- c(1995)

main_df <-data.frame(year_eventA)
df1 <-data.frame(year_eventB)
df2 <-data.frame(year_eventC)

I want to add a column to my main data frame that will specify weather event B occurred and another column that will do the same thing for event C.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example

year_eventA Event B Event C
1995 0 1
1996 0 0
1997 1 0
1998 0 0
1999 1 0

I am not sure how to do this. I thought of using for loops, but I’m just starting to learn R after working with python and am not sure how things would translate.

>Solution :

One way to create these two new variables:

EventB <- (year_eventA %in% year_eventB) + 0L
#[1] 0 0 1 0 1

EventC <- (year_eventA %in% year_eventC) + 0L
#[1] 1 0 0 0 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading