0

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:

  1. The matrices are of different numbers of rows. And each matrix may contain subjects that do not appear in the other.
  2. 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
curbholes
  • 557
  • 2
  • 5
  • 11
  • 1
    Lookup "how to do an inner/outer join with R". Simplest solution is to use `merge` which is in base R. – asachet Oct 13 '15 at 12:24

1 Answers1

1

Use merge:

merge(x=a,y = b, by.x="subject", by.y = "subject")

  subject value 1.x value 2 value 1.y
1       1       100      10        NA
2       2       200      20        NA
3       4       400      40        NA
4       6       600      60        NA
5       7       700      70        NA
6       8       800      80        NA
7       9       900      90        NA
R. Schifini
  • 9,085
  • 2
  • 26
  • 32
  • Thanks! But now there is all the subjects missing from matrix b who do not appear in matrix a. – curbholes Oct 13 '15 at 12:33
  • 1
    There is an option in merge that is `all.x =` and `all.y =` and take values true or false. This will include columns that have no match from the corresponding data frame. Read `?merge` for more details and options. – R. Schifini Oct 13 '15 at 13:13