我有以下data frame
:
Date CCL Rie
2002-01-01 68.6879472 MB
2002-02-01 38.1691072 MB
2002-03-01 53.2893517 MB
2002-04-01 16.9071572 MA
2002-05-01 8.9496654 A
2002-06-01 37.1852996 MB
2002-07-01 39.0751017 MB
2002-08-01 16.4683628 MA
2002-09-01 18.9381392 MA
2002-10-01 18.7873039 MA
2002-11-01 39.9079079 MB
我还没有找到代码或包来获取下一个输出:
Date New Column
2002-01-01 68.6879472
2002-01-01 MB
2002-02-01 38.1691072
2002-02-01 MB
2002-03-01 53.2893517
2002-03-01 MB
2002-04-01 16.9071572
2002-04-01 MA
等等......
即,对于相同的date
,请创建一个新列,该列会抛出CCL
和Rie
插入的值
答案 0 :(得分:3)
或者使用base reshape
:
tt <- reshape(data = df, idvar="Date", varying = c("CCL", "Rie"),
direction="long", v.names=c("values"))[c("Date", "values")]
> tt[order(tt$Date), ]
# Date values
# 2002-01-01.1 2002-01-01 68.6879472
# 2002-01-01.2 2002-01-01 MB
# 2002-02-01.1 2002-02-01 38.1691072
# 2002-02-01.2 2002-02-01 MB
# 2002-03-01.1 2002-03-01 53.2893517
# 2002-03-01.2 2002-03-01 MB
# 2002-04-01.1 2002-04-01 16.9071572
# 2002-04-01.2 2002-04-01 MA
# 2002-05-01.1 2002-05-01 8.9496654
# 2002-05-01.2 2002-05-01 A
# 2002-06-01.1 2002-06-01 37.1852996
# 2002-06-01.2 2002-06-01 MB
# 2002-07-01.1 2002-07-01 39.0751017
# 2002-07-01.2 2002-07-01 MB
# 2002-08-01.1 2002-08-01 16.4683628
# 2002-08-01.2 2002-08-01 MA
# 2002-09-01.1 2002-09-01 18.9381392
# 2002-09-01.2 2002-09-01 MA
# 2002-10-01.1 2002-10-01 18.7873039
# 2002-10-01.2 2002-10-01 MA
# 2002-11-01.1 2002-11-01 39.9079079
# 2002-11-01.2 2002-11-01 MB
答案 1 :(得分:2)
您可以使用melt
包中的reshape2
功能执行此操作:
d <- melt(d, id.vars="Date")
d[order(d$Date),-which(colnames(d)=="variable")]
给出了:
Date value
1 2002-01-01 68.6879472
12 2002-01-01 MB
2 2002-02-01 38.1691072
13 2002-02-01 MB
3 2002-03-01 53.2893517
14 2002-03-01 MB
4 2002-04-01 16.9071572
15 2002-04-01 MA
5 2002-05-01 8.9496654
16 2002-05-01 A
6 2002-06-01 37.1852996
17 2002-06-01 MB
7 2002-07-01 39.0751017
18 2002-07-01 MB
8 2002-08-01 16.4683628
19 2002-08-01 MA
9 2002-09-01 18.9381392
20 2002-09-01 MA
10 2002-10-01 18.7873039
21 2002-10-01 MA
11 2002-11-01 39.9079079
22 2002-11-01 MB