简体   繁体   中英

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

Here is my 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 to reshape it into 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 you can use dplyr with 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

you can use reshape2 library and function melt . Here is an example. You can melt by ID variables:

library(reshape2)
data <- data.frame(year=rep("2013", 5), period=seq(1,5), day1=seq(2,6), day2=seq(3,7))
data <- melt(data, id.vars=c("year", "period"))

Or you can melt by measure variables:

data <- melt(data, measure.vars=c("day1", "day2"))

You just have to drop one unnecessary column

data <- data[,-3]

1) Using base R

reshape(d, varying = paste0("Day", 1:7), sep = "", direction = "long")

2) An alternative, using tidyr

gather(d, id, Day, Day1:Day7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM