-1

下面是我的代码

### makes indiviual matrix of data ##
#####READ IN FILES##########
one<-matrix(c(2001,2002,2003,2004,23456, 23567,54321,12345),4,2);
two<-matrix(c(54321,23567,23456,12345,1234,2345,3456,7777),4,2);
three<-matrix(c(3456,7777,2345,1234,5677,6789,6678,6767),4,2);
four<-matrix(c(6678,5677,6767,5555,1111,1112),4,2);
 five<-matrix(c(5555,1112,1111,2222,1212,9999),4,2);
## order all data by second column and spit out NAs if number in second column of 
## previous matrix  doesnt match first column of new matrix
onea<-one[order(one[,2]),];
twoa<-two[order(two[,1])[rank(onea[,2])],];
threea<-three[order(three[,1])[rank(twoa[,2])],]
foura<-four[order(four[,1])[rank(threea[,2])],]
fivea<-five[order(five[,1])[rank(foura[,2])],]
finaltable<-cbind(onea,twoa,threea,foura,fivea)

这些是我收到的警告消息:

Warning message:
In matrix(c(6678, 5677, 6767, 5555, 1111, 1112), 4, 2) :
  data length [6] is not a sub-multiple or multiple of the number of rows [4]
>     five<-matrix(c(5555,1112,1111,2222,1212,9999),4,2);
Warning message:
In matrix(c(5555, 1112, 1111, 2222, 1212, 9999), 4, 2) :
  data length [6] is not a sub-multiple or multiple of the number of rows [4]

我想要做的是,当我从 threea[,2] 的排名中 order(four[,1]) 时,我有一个缺失值。每当在foura [,1]中不再找到threea [,2]中的数字时,我希望它在该数字的对面说NA。下面是我想说的。如果可能的话,我需要它非常自动化。此外,NA 值需要能够在整个表格中不影响其他相互匹配的数字。

finaltable
     [,1]  [,2]  [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2004 12345 12345 7777 7777 6789 NA     NA   NA    NA
[2,] 2001 23456 23456 3456 3456 5677 5677 1111 1111  8888
[3,] 2002 23567 23567 2345 2345 6678 6678 5555 5555  2222
[4,] 2003 54321 54321 1234 1234 6767 6767 1112 1112  9999
4

1 回答 1

1

这个问题很不清楚。我之所以能够关注,是因为您昨天问了一个我记得的类似问题。希望这能回答你的问题。

首先,您创建的矩阵不正确。你真正想要的是什么(我认为)fourfive这是:

four<-matrix(c(6678,5677,6767,5555,1111,1112),3,2)
five<-matrix(c(5555,1112,1111,2222,1212,9999),3,2)

你的第二个问题可以这样解决:

 matchOrder<-function(x,y){
   y[match(x[,2],y[,1]),]
 }
 onea <- one[order(one[,2]),]
 twoa <- matchOrder(onea,two)
 threea <- matchOrder(twoa,three)
 foura <- matchOrder(threea,four)
 fivea <- matchOrder(foura,five)
 finaltable <- cbind(onea,twoa,threea,foura,fivea)
 finaltable
     [,1]  [,2]  [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2004 12345 12345 7777 7777 6789   NA   NA   NA    NA
[2,] 2001 23456 23456 3456 3456 5677 5677 1111 1111  9999
[3,] 2002 23567 23567 2345 2345 6678 6678 5555 5555  2222
[4,] 2003 54321 54321 1234 1234 6767 6767 1112 1112  1212

实际上,您真正想做的是将这些矩阵放在一个列表中,然后一次调用即可完成所有操作:

l <- list(two,three,four,five)
do.call(cbind,Reduce(matchOrder,l,onea,accumulate=T))
     [,1]  [,2]  [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2004 12345 12345 7777 7777 6789   NA   NA   NA    NA
[2,] 2001 23456 23456 3456 3456 5677 5677 1111 1111  9999
[3,] 2002 23567 23567 2345 2345 6678 6678 5555 5555  2222
[4,] 2003 54321 54321 1234 1234 6767 6767 1112 1112  1212
于 2013-10-14T21:19:30.413 回答