这是我的广泛数据
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
我希望将其重塑为
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
答案 0 :(得分:3)
尝试:
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
或者您可以将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
答案 1 :(得分:1)
您可以使用reshape2
库和函数melt
。这是一个例子。您可以通过ID变量进行融合:
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"))
或者你可以通过测量变量来融化:
data <- melt(data, measure.vars=c("day1", "day2"))
你只需删除一个不必要的列
data <- data[,-3]
答案 2 :(得分:1)
1)使用基础R
reshape(d, varying = paste0("Day", 1:7), sep = "", direction = "long")
2)另一种方法,使用tidyr
gather(d, id, Day, Day1:Day7)