[R] Reshape
arun
smartpink111 at yahoo.com
Thu Oct 17 07:25:58 CEST 2013
HI,
A minor change to make it a bit more generic.
res <- reshape(ddply(df,.(Person), mutate,id=((seq_along(Person)-1)%%2+1)),idvar=c("Person","Date"),timevar="id",direction="wide")
colnames(res)[3:4] <- paste0("Amt",1:2)
rownames(res) <- 1:nrow(res)
In cases like:
df1 <- rbind(df,data.frame(Person=2,Amount=50,Date="12/02/2012"))
res1 <- reshape(ddply(df1,.(Person), mutate,id=((seq_along(Person)-1)%%2+1)),idvar=c("Person","Date"),timevar="id",direction="wide")
colnames(res1)[3:4] <- colnames(res)[3:4]
rownames(res1) <- 1:nrow(res1)
res1
# Person Date Amt1 Amt2
#1 1 12/01/2012 100 10
#2 1 01/01/2013 100 10
#3 1 02/01/2013 100 10
#4 2 12/01/2012 50 150
#5 2 12/02/2012 50 NA
A.K.
On Thursday, October 17, 2013 12:53 AM, arun <smartpink111 at yahoo.com> wrote:
Hi,
Try:
library(plyr)
res <- reshape(ddply(df,.(Person),mutate,id=rep(1:2,length(Person)/2)),idvar=c("Person","Date"),timevar="id",direction="wide")
colnames(res)[3:4] <- paste0("Amt",1:2)
rownames(res) <- 1:nrow(res)
res
# Person Date Amt1 Amt2
#1 1 12/01/2012 100 10
#2 1 01/01/2013 100 10
#3 1 02/01/2013 100 10
#4 2 12/01/2012 50 150
A.K.
On Wednesday, October 16, 2013 11:54 PM, Kimberly Harris-McCoy <kmcreed32 at hotmail.com> wrote:
Hello,
I have data frame like the one created below,
##input data
Person <- c(1,1,1,1,1,1,2,2)
Amount <- c(100,10,100,10,100,10,50,150)
Date <- c("12/01/2012", "12/01/2012", "01/01/2013","01/01/2013","02/01/2013","02/01/2013","12/01/2012","12/01/2012")
df <- data.frame(Person,Amount,Date)
I would like to transpose the Amount data so that I can get the total amount paid by person and date.
So, it would look something like:
##Want it to look like:
Person Date Amt1 Amt2
1 12/01/2012 100 10
1 01/01/2013 100 10
1 02/01/2013 100 10
2 12/01/2012 50 150
I have been working with reshape, but I am having trouble getting it to look exactly right.
Thank you,
K
______________________________________________
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