Message-ID: <1350675201.27680.YahooMailNeo@web142601.mail.bf1.yahoo.com>
Date: 2012-10-19T19:33:21Z
From: arun
Subject: Creating a new by variable in a dataframe
In-Reply-To: <1350669095329-4646782.post@n4.nabble.com>
Hi,
May be this helps you:
dat1<-read.table(text="
tdate? event_tim? transaction
1/10/2012?? 2?? 14
1/10/2012?? 4?? 28
1/10/2012?? 6?? 42
1/10/2012?? 8?? 14
2/10/2012?? 6?? 46
2/10/2012?? 9?? 64
2/10/2012?? 8?? 71
3/10/2012? 3?? 85
3/10/2012?? 1?? 14
3/10/2012?? 4?? 28
9/10/2012?? 5?? 51
9/10/2012?? 9?? 66
9/20/2012? 12?? 84
",sep="",header=TRUE,stringsAsFactors=FALSE)
dat2<-dat1[with(dat1,order(tdate,event_tim)),]
dat2$tdate<-as.Date(dat2$tdate,format="%m/%d/%Y")
dat3<-dat2
?dat3$last_trans<-NA
library(plyr)
dat4<-merge(dat3,ddply(dat2,.(tdate),tail,1))
dat4$last_trans<-dat4$transaction
?res<-merge(dat4,dat2,all=TRUE)
?res
#??????? tdate event_tim transaction last_trans
#1? 2012-01-10???????? 2????????? 14???????? NA
#2? 2012-01-10???????? 4????????? 28???????? NA
#3? 2012-01-10???????? 6????????? 42???????? NA
#4? 2012-01-10???????? 8????????? 14???????? 14
#5? 2012-02-10???????? 6????????? 46???????? NA
#6? 2012-02-10???????? 8????????? 71???????? NA
#7? 2012-02-10???????? 9????????? 64???????? 64
#8? 2012-03-10???????? 1????????? 14???????? NA
#9? 2012-03-10???????? 3????????? 85???????? NA
#10 2012-03-10???????? 4????????? 28???????? 28
#11 2012-09-10???????? 5????????? 51???????? NA
#12 2012-09-10???????? 9????????? 66???????? 66
#13 2012-09-20??????? 12????????? 84???????? 84
----- Original Message -----
From: ramoss <ramine.mossadegh at finra.org>
To: r-help at r-project.org
Cc:
Sent: Friday, October 19, 2012 1:51 PM
Subject: [R] Creating a new by variable in a dataframe
Hello,
I have a dataframe w/ 3 variables of interest: transaction,date(tdate) &
time(event_tim).
How could I create a 4th variable (last_trans) that would flag the last
transaction of the day for each day?
In SAS I use:
proc sort data=all6;
by tdate event_tim;
run;
? ? ? ? /*Create last transaction flag per day*/
data all6;
? set all6;
? by tdate event_tim;
? last_trans=last.tdate;
Thanks ahead for any suggestions.
--
View this message in context: http://r.789695.n4.nabble.com/Creating-a-new-by-variable-in-a-dataframe-tp4646782.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.