从列中排序并将其粘贴到另一行

时间:2016-01-04 03:03:43

标签: r

我有一组数据如下:

ID  Distance
0   270.4170919
0   240.0230499
0   270.5878873
0   260.3663412
0   88.81341556
1   5564.323783
1   5625.862105
1   5709.559224
1   5809.231131
1   6286.892713
2   326.8418382
2   439.2376606
2   427.4494778
2   327.625258
2   326.3938459
3   601.9958829
3   323.1702281
3   755.3196593

有五行ID 0,1..325及其对应的值(距离)。我想根据行(距离)值拆分列(ID)并粘贴到多行,如下所示:

    A           B           C           D           E
0   88.81341556 240.0230499 260.3663412 270.4170919 270.5878873
1   5564.323783 5625.862105 5709.559224 5809.231131 6286.892713
2   326.3938459 326.8418382 327.625258  427.4494778 439.2376606
3   323.1702281 334.7788259 601.9958829 710.3485862 755.3196593

我不知道在哪里以及如何开始编码。

2 个答案:

答案 0 :(得分:4)

您可以根据ID进行拆分,然后对每个拆分进行排序。然后将其转置以匹配您想要输出的矩阵。

t(sapply(split(d$Distance, d$ID), sort))
#        [,1]      [,2]      [,3]      [,4]      [,5]
#0   88.81342  240.0230  260.3663  270.4171  270.5879
#1 5564.32378 5625.8621 5709.5592 5809.2311 6286.8927
#2  326.39385  326.8418  327.6253  427.4495  439.2377
#3  323.17023  334.7788  601.9959  710.3486  755.3197

一些替代方案:

t(apply(matrix(d$Distance, nrow=5), 2, sort)) # rows aren't named here

do.call(rbind, lapply(split(d$Distance, d$ID), sort))

matrix(d[with(d, order(ID, Distance)), "Distance"], 
  ncol = 5, 
  byrow = TRUE, 
  dimnames = list(unique(d$ID))) # make sure IDs are in the right order

示例数据(注意,提供的示例数据缺少ID 3中的两个值,我在这里的示例数据中添加了它们):

d <- read.table(text="
ID  Distance
0   270.4170919
0   240.0230499
0   270.5878873
0   260.3663412
0   88.81341556
1   5564.323783
1   5625.862105
1   5709.559224
1   5809.231131
1   6286.892713
2   326.8418382
2   439.2376606
2   427.4494778
2   327.625258
2   326.3938459
3   601.9958829
3   323.1702281
3   755.3196593
3   334.7788259
3   710.3485862", header=TRUE)

答案 1 :(得分:4)

以下是使用unstack

的其他选项
 t(unstack(d[do.call(order, d),], Distance~ID))
 #       [,1]      [,2]      [,3]      [,4]      [,5]
 #X0   88.81342  240.0230  260.3663  270.4171  270.5879
 #X1 5564.32378 5625.8621 5709.5592 5809.2311 6286.8927
 #X2  326.39385  326.8418  327.6253  427.4495  439.2377
 #X3  323.17023  334.7788  601.9959  710.3486  755.3197

dcast

中的data.table
 library(data.table)
 dcast(setDT(d)[order(ID, Distance)][, N:= 1:.N ,ID],
                        N~ID, value.var='Distance')[, N:= NULL]

注意:我们得到的输出需要像之前一样进行转换。