按降序排列多列并指定日期值

时间:2016-02-09 18:27:17

标签: r

我想按降序排序(data1,data2和data3),之后我想在(data1,data2和data3)列中分配相应的日期而不是值。

 date    data1  data2 data3
 1970/1  5        8    7
 1971/1  7        4    2
 1972/1  3        3    4
 1973/1  2        0    54
 1974/1  0        50   12
 1975/1  8        8    6
 1976/1  10       2    4
 1977/1  20       3    1

我想得到像这样的输出

data1   data2   data3
1977/1  1974/1  1973/1
1976/1  1970/1  1974/1
1975/1  1975/1  1970/1
1971/1  1971/1  1975/1
1970/1  1972/1  1972/1
1972/1  1977/1  1976/1
1973/1  1976/1  1971/1
1974/1  1973/1  1977/1

2 个答案:

答案 0 :(得分:3)

哦,稍晚......

apply(df[,2:4], 2, function(d) df$date[order(d, decreasing = TRUE)])

答案 1 :(得分:0)

这是圆润的方式来做到这一点.. @ stephen解决方案是要走的路。

df <- data.frame(date,data1,data2,data3)
rownames(df) <- df$date 

df1 <- df[order(df$data1, decreasing = TRUE), ]
df$data1 <- rownames(df1)

df2 <- df[order(df$data2, decreasing = TRUE), ]
df$data2 <- rownames(df2)

df3 <- df[order(df$data3, decreasing = TRUE), ]
df$data3 <- rownames(df3)
new.df <- subset(df, select = data1:data3)
rownames(new.df) <- NULL
new.df

   data1  data2  data3
1 1977/1 1974/1 1973/1
2 1976/1 1970/1 1974/1
3 1975/1 1975/1 1970/1
4 1971/1 1971/1 1975/1
5 1970/1 1972/1 1972/1
6 1972/1 1977/1 1976/1
7 1973/1 1976/1 1971/1
8 1974/1 1973/1 1977/1