I have two matrices, two columns each. The first column is the subject number, the second column the appropriate measurement of the subject. I want to add the values of the first matrix ("value 1") to the second matrix but in the right position. I.e. in the position belonging to the correct subject. There is two problems:
- The matrices are of different numbers of rows. And each matrix may contain subjects that do not appear in the other.
- The subject numbers in the first matrix are not ordered.
I tried to do it with a for-loop:
a1<-c(1,18,2,6,25,8,9,7,4)
b1<-seq(1:15)
a2<-a1*100
b2<-seq(from=10,to=150,by=10)
a<-cbind(a1,a2)
b<-cbind(b1,b2,NA)
colnames(a)<-(c("subject","value 1"))
colnames(b)<-(c("subject","value 2","value 1"))
length_b<-length(b[,1])
for (i in length_b)
{
present<-(b[i,1] %in% a[,1])
if (present==TRUE)
{
location[i]<-which(a[,1]==b[i,1])
b[i,3]<-a[location,2]
}
}
But then b still looks like this:
subject value 2 value 1
[1,] 1 10 NA
[2,] 2 20 NA
[3,] 3 30 NA
[4,] 4 40 NA
[5,] 5 50 NA
[6,] 6 60 NA
[7,] 7 70 NA
[8,] 8 80 NA
[9,] 9 90 NA
[10,] 10 100 NA
[11,] 11 110 NA
[12,] 12 120 NA
[13,] 13 130 NA
[14,] 14 140 NA
[15,] 15 150 NA