Reputation: 25
I have an 'Exp' data set which looks like this:
Locals Res Ind
1 112 7.865 4.248
2 113 4.248 5.666
3 114 5.666 2.444
4 115 2.444 7.865
5 116 7.865 4.248
6 117 4.248 6.983
7 118 5.666 3.867
8 119 2.444 2.987
And I have another data set called 'Com' as below:
113 112 113
112 114 119
116 118 119
118 118 119
117 117 119
117 117 119
I want to create two matrices called 'Res' and 'Ind' based on the value in the Com data, match it to the first row, Local, of the Exp data and get the corresponding value from the 'Res' or 'Ind' column depending on the matrix it is created for. For eg - The first value in the Com data set is 113 so in the Res matrix the first value will be 4.248 - because the corresponding value in Exp's first column of 113 is 4.248. Such that the Res matrix will look something like this
4.248 7.865 4.248
7.865 5.666 2.444
7.865 5.666 2.444
5.666 5.666 2.444
4.248 4.248 2.444
4.248 4.248 2.444
Can anybody please suggest a easy way to do this on R. If there are many matrices required to be created and many values in Exp's first row then what is the quickest way to do this?
Thanks in advance
Upvotes: 0
Views: 63
Reputation: 79338
structure(dat1$Res[match(unlist(dat2),dat1[,1])],.Dim=dim(dat2))
[1,] 4.248 7.865 4.248
[2,] 7.865 5.666 2.444
[3,] 7.865 5.666 2.444
[4,] 5.666 5.666 2.444
[5,] 4.248 4.248 2.444
[6,] 4.248 4.248 2.444
structure(dat1$Ind[match(unlist(dat2),dat1[,1])],.Dim=dim(dat2))
[,1] [,2] [,3]
[1,] 5.666 4.248 5.666
[2,] 4.248 2.444 2.987
[3,] 4.248 3.867 2.987
[4,] 3.867 3.867 2.987
[5,] 6.983 6.983 2.987
[6,] 6.983 6.983 2.987
You can do this in one line:
lapply(Exp[-1],function(x) structure(x[match(as.matrix ( Com),Exp[,1])],.Dim=dim(Com)))
$Res
[,1] [,2] [,3]
[1,] 4.248 7.865 4.248
[2,] 7.865 5.666 2.444
[3,] 7.865 5.666 2.444
[4,] 5.666 5.666 2.444
[5,] 4.248 4.248 2.444
[6,] 4.248 4.248 2.444
$Ind
[,1] [,2] [,3]
[1,] 5.666 4.248 5.666
[2,] 4.248 2.444 2.987
[3,] 4.248 3.867 2.987
[4,] 3.867 3.867 2.987
[5,] 6.983 6.983 2.987
[6,] 6.983 6.983 2.987
Upvotes: 1