I have two dataframes and I want to add two columns AGE and IQ from the data2 dataframe to the data1 dataframe only for matching ID. Here is an example of the two dataframes:
data1= structure(list(ID = c(1L, 2L, 3L, 4L, 5L), CONDITION = structure(c(1L, 1L, 1L, 2L, 2L), .Label=c("ANX","ADHD"), class = "factor")), class = "data.frame", row.names = c(NA, -5L))
data2= structure(list(ID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L), CONDITION = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 3L), .Label=c("ANX","ADHD", "COM"), class = "factor"), AGE = c(7L, 8L, 8L, 9L, 9L, 10L, 11L), IQ =c(78L, 83L, 116L, 90L, 80L, 85L, 87L)), .Names= c("ID", "CONDITION", "AGE", "IQ"), class = "data.frame", row.names = c(NA, -7L))
So far i have tried something like:
merge(data1, data2[, c("AGE", "IQ")], by= "ID")
Any help will be much appreciated! Thanks in advance.