Monday, 15 September 2014

r - I want to reshape the following wide data frame as into long -



r - I want to reshape the following wide data frame as into long -

here wide data

year period day1 day2 day3 day4 day5 day6 day7 1 1995 1 1995-01-02 1995-01-03 1995-01-04 1995-01-05 1995-01-06 1995-01-07 1995-01-08 2 1995 2 1995-01-09 1995-01-10 1995-01-11 1995-01-12 1995-01-13 1995-01-14 1995-01-15 3 1995 3 1995-01-16 1995-01-17 1995-01-18 1995-01-19 1995-01-20 1995-01-21 1995-01-22 4 1995 4 1995-01-23 1995-01-24 1995-01-25 1995-01-26 1995-01-27 1995-01-28 1995-01-29 5 1995 5 1995-01-30 1995-01-31 1995-02-01 1995-02-02 1995-02-03 1995-02-04 1995-02-05 6 1995 6 1995-02-06 1995-02-07 1995-02-08 1995-02-09 1995-02-10 1995-02-11 1995-02-12

i want reshape long as

year period day 1995 1 1995-01-02 1995 1 1995-01-03 1995 1 1995-01-04 1995 1 1995-01-05 1995 1 1995-01-06 1995 1 1995-01-07 1995 1 1995-01-08 1995 2 1995-01-09 1995 2 1995-01-10 1995 2 1995-01-11 1995 2 1995-01-12 1995 2 1995-01-13 1995 2 1995-01-14 1995 2 1995-01-15

try:

library(reshape2) mdat <- melt(dat, id.var=c("year", "period"))[,-3] mdat1 <- mdat[order(mdat$year, mdat$period),] row.names(mdat1) <- 1:nrow(mdat1) head(mdat1) # year period value #1 1995 1 1995-01-02 #2 1995 1 1995-01-03 #3 1995 1 1995-01-04 #4 1995 1 1995-01-05 #5 1995 1 1995-01-06 #6 1995 1 1995-01-07

or can utilize dplyr tidyr

library(dplyr) library(tidyr) dat%>% gather(var, day, starts_with("day")) %>% select(-var) %>% arrange(year, period) %>% head() #year period day #1 1995 1 1995-01-02 #2 1995 1 1995-01-03 #3 1995 1 1995-01-04 #4 1995 1 1995-01-05 #5 1995 1 1995-01-06 #6 1995 1 1995-01-07

r reshape

No comments:

Post a Comment