[R] match values in dependence of ID and Date

arun smartpink111 at yahoo.com
Thu Oct 17 16:08:57 CEST 2013


Hi,

I think based on your title, the output you provided is not clear. If it depends on Date, there should be four columns.
library(reshape2)

res1 <- dcast(merge(dat,dat2,by="ID"),ID+Name~Date,value.var="Value")
 colnames(res1)[3:6] <- c("First", "Second", "Third", "Fourth")
 rownames(res1) <- 1:nrow(res1)


#or
res2 <- reshape(merge(dat,dat2,by="ID"),idvar=c("ID","Name"),timevar="Date",direction="wide")
 dimnames(res2) <- dimnames(res1)

 res2
#  ID Name First Second Third Fourth
#1  1 Andy    10     15    NA     NA
#2  2 John     7     NA    10     15
#3  3  Amy    10     NA    NA     NA


A.K.






On Thursday, October 17, 2013 9:31 AM, arun <smartpink111 at yahoo.com> wrote:
Hi,
Try:
dat <- read.table(text="
ID    Name
1    Andy
2    John
3    Amy",sep="",header=TRUE,stringsAsFactors=FALSE)

dat2 <- read.table(text="
ID  Date            Value
1    2013-10-01    10
1    2013-10-02    15
2    2013-10-01    7
2    2013-10-03    10
2    2013-10-04    15
3    2013-10-01    10",sep="",header=TRUE,colClasses=c("numeric","Date","numeric"))

library(plyr)

 res <- reshape(ddply(merge(dat,dat2,by="ID"),.(ID),mutate,id=((seq_along(ID)-1)%%3+1))[,-3],idvar=c("ID","Name"),timevar="id",direction="wide")
 rownames(res) <- 1:nrow(res)
 colnames(res)[3:5] <- c("First", "Second", "Third")

 res
#  ID Name First Second Third
#1  1 Andy    10     15    NA
#2  2 John     7     10    15
#3  3  Amy    10     NA    NA
A.K.







On Thursday, October 17, 2013 7:42 AM, Mat <matthias.weber at fnt.de> wrote:
hello togehter,

i have a little problem, maybe you can help me.

I have a data.frame like this one:

ID    Name
1     Andy
2     John
3     Amy

and a data.frame like this:

ID   Date            Value
1    2013-10-01    10
1    2013-10-02    15
2    2013-10-01    7
2    2013-10-03    10
2    2013-10-04    15
3    2013-10-01    10

the result should be this one:

ID    Name   First   Second    Third
1     Andy    10     15
2     John     7      10           15
3     Amy     10

maybe you can help me, to do this?

Thank you.

Mat



--
View this message in context: http://r.789695.n4.nabble.com/match-values-in-dependence-of-ID-and-Date-tp4678433.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