[R] create new column to combine 2 data.frames
Mat
matthias.weber at fnt.de
Fri Aug 30 11:27:11 CEST 2013
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.
More information about the R-help
mailing list