[R] create new column to combine 2 data.frames
Rui Barradas
ruipbarradas at sapo.pt
Fri Aug 30 11:06:32 CEST 2013
Hello,
Suposing that your data frames are named dat1 and dat2, the following
works, but it's a bit complicated, maybe there are simpler solutions.
dat1 <- read.table(text = "
ID Name
1 Jack
2 John
3 Jill
", header = TRUE, stringsAsFactors = FALSE)
dat2 <- read.table(text = "
ID Days Type
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
Hope this helps,
Rui Barradas
Em 30-08-2013 09:37, Mat escreveu:
> Hello together i have a little problem with the combine of two data.frames.
>
> I have 2 data.frames, which look like this one:
>
> first dataframe:
> ID Name
> 1 Jack
> 2 John
> 3 Jill
>
> second dataframe
> ID Days Type
> 1 3 Training
> 2 1 Management
> 3 4 Training
>
> At the end i want to create a data.frame like this one (the Type should be
> the new column and the entry of the column should be the days):
>
> ID Name Training Management
> 1 Jack 3 0
> 2 John 0 1
> 3 Jill 4 0
>
> maybe anyone can help me, how i can do this.
>
> Thanks a lot.
>
> Best regards. Mat
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/create-new-column-to-combine-2-data-frames-tp4674963.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