[R] create new column to combine 2 data.frames

Rui Barradas ruipbarradas at sapo.pt
Fri Aug 30 12:31:42 CEST 2013


Hello,

Ok, try instead



library(reshape2)
tmp <- dcast(data = dat2, ID ~ Type, value.var = "Type")

tmp[-1] <- lapply(tmp[-1], function(x){
	y <- integer(length(x))
	s <- as.character(x[!is.na(x)])[1]
	idx <- which(as.character(dat2[["Type"]]) == s)
	y[!is.na(x)] <- dat2[["Days"]][idx]
	y})

result <- merge(dat1, tmp)
result


Rui Barradas

Em 30-08-2013 10:27, Mat escreveu:
> 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 at 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.
>



More information about the R-help mailing list