Hi Sorry, I did not read your question to the end
library(reshape) merge(dat1,cast(melt(dat2, c("ID", "Type")), ID~Type)) ID Name Management Training 1 1 Jack 1 3 2 2 John 1 NA 3 3 Jill NA 4 Is close enough, you can easily change NA to 0 if you want. Regards Petr > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-bounces@r- > project.org] On Behalf Of Mat > Sent: Friday, August 30, 2013 11:27 AM > To: r-help@r-project.org > Subject: Re: [R] create new column to combine 2 data.frames > > Thanks first. > > that doesn't look bad. But if have a equal ID in dat2, the days are no > longer correct. > > the correct data.frame has to look like this one: > > ID Name Management Training > 1 1 Jack 1 3 > 2 2 John 1 0 > 3 3 Jill 0 4 > > not this one: > > ID Name Management Training > 1 1 Jack 1 1 > 2 2 John 3 0 > 3 3 Jill 0 1 > > > dat1 <- read.table(text = " > + ID Name > + 1 Jack > + 2 John > + 3 Jill > + ", header = TRUE, stringsAsFactors = FALSE) > > > > dat2 <- read.table(text = " > + ID Days Type > + 1 1 Management > + 1 3 Training > + 2 1 Management > + 3 4 Training > + ", header = TRUE, stringsAsFactors = FALSE) > > > > library(reshape2) > > tmp <- dcast(data = dat2, ID ~ Type, value.var = "Type") > > > > tmp[-1] <- lapply(tmp[-1], function(x){ > + y <- integer(length(x)) > + y[!is.na(x)] <- dat2[["Days"]][!is.na(x)] > + y}) > > result <- merge(dat1, tmp) > > result > ID Name Management Training > 1 1 Jack 1 1 > 2 2 John 3 0 > 3 3 Jill 0 1 > > > > > > -- > View this message in context: http://r.789695.n4.nabble.com/create-new- > column-to-combine-2-data-frames-tp4674963p4674968.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting- > guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.