1

我有以下内容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,创建一个新列,该列抛出CCLRie插入的值

4

2 回答 2

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
于 2013-03-14T15:26:36.887 回答
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
于 2013-03-14T15:21:49.063 回答