[R] combine two columns into one
arun
smartpink111 at yahoo.com
Wed May 29 21:08:57 CEST 2013
dat1<- read.table(text="
Date Time Var
11/1/2012 1 3
11/1/2012 1 1
11/1/2012 1 1
11/1/2012 2 3
11/1/2012 2 1
11/1/2012 2 1
11/2/2012 1 1
11/2/2012 1 3
11/2/2012 1 1
11/2/2012 2 3
",sep="",header=TRUE,stringsAsFactors=FALSE)
dat1$Date<-as.Date(dat1$Date,format="%m/%d/%Y")
If you need to combine Date and Time columns into one:
library(plyr)
res<-mutate(ddply(dat1,.(Date,Time),summarize,Var=sum(Var)),DT=paste(Date,Time,sep="_"))[,c(4,3)]
res
# DT Var
#1 2012-11-01_1 5
#2 2012-11-01_2 5
#3 2012-11-02_1 5
#4 2012-11-02_2 3
A.K.
________________________________
From: Ye Lin <yelin at lbl.gov>
To: arun <smartpink111 at yahoo.com>
Cc: R help <r-help at r-project.org>
Sent: Wednesday, May 29, 2013 2:40 PM
Subject: Re: [R] combine two columns into one
The actual "date" col is in yyyy-mm-dd format, and when I apply this code to my actual data, it mess up the order
On Wed, May 29, 2013 at 11:37 AM, arun <smartpink111 at yahoo.com> wrote:
>
>Hi,
>May be I misunderstood your question:
>dat<- read.table(text="
>
>Date Time Var
>1 1 2
>1 1 4
>1 1 5
>1 2 8
>1 2 8
>1 2 9
>2 1 3
>2 1 4
>2 1 4
>",sep="",header=TRUE)
>
>dat$UniqueID <- paste(dat$Date,dat$Time, sep = '_')
> aggregate(dat$Var,list(dat$UniqueID),sum) #isn't this the correct order
># Group.1 x
>#1 1_1 11
>#2 1_2 25
>#3 2_1 11
>library(plyr)
>ddply(dat,.(UniqueID),summarize,Var=sum(Var))
># UniqueID Var
>#1 1_1 11
>#2 1_2 25
>#3 2_1 11
>A.K.
>
>
>
>
>----- Original Message -----
>From: Ye Lin <yelin at lbl.gov>
>To: R help <r-help at r-project.org>
>Cc:
>Sent: Wednesday, May 29, 2013 2:23 PM
>Subject: [R] combine two columns into one
>
>Hey all!
>
>I have a time series dataset like this:
>
>Date Time Var
>1 1 2
>1 1 4
>1 1 5
>1 2 8
>1 2 8
>1 2 9
>2 1 3
>2 1 4
>2 1 4
>
>I created a unique id for each row:
>dat$UniqueID <- paste(dat$Date,dat$Time, sep = '_')
>
>then
>
>aggregate(dat$Var, list(dat$UniqueID), sum)
>
>however the final output is not in ideal order I look for (I simply this
>example provided above).I would like to have order like this:
>
>1_1
>1_2
>2_1
>
>Thanks for your help!
>
> [[alternative HTML version deleted]]
>
>______________________________________________
>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