My trial data is given as follows:
testdata = matrix(c(1,1,1,2,2,3,3,3,10,11,12,13,
14,15,16,17,28,30,25,40,50,47,62,23),ncol=3,byrow=F)
colnames(testdata)=c("index","contact","age")
testdata
#> index contact age
#> [1,] 1 10 28
#> [2,] 1 11 30
#> [3,] 1 12 25
#> [4,] 2 13 40
#> [5,] 2 14 50
#> [6,] 3 15 47
#> [7,] 3 16 62
#> [8,] 3 17 23
From the given data, I want create a matrix similar to an adjacency matrix as follows.
adjmat = matrix(c(0,0,0,28,30,25,rep(0,11),40,50,
rep(0,11),47,62,23,28, rep(0,10),30,rep(0,10),25, rep(0,11), 40, rep(0,10),50,
rep(0,11),47, rep(0,10), 62,rep(0,10), 23, rep(0,8)),ncol=11,byrow=T,
dimnames = list(c("1", "2","3","10","11","12","13","14","15","16","17"),
c("1","2","3","10","11","12","13","14","15","16","17")))
That means in matrix form it will be as follows:
adjmat
#> 1 2 3 10 11 12 13 14 15 16 17
#> 1 0 0 0 28 30 25 0 0 0 0 0
#> 2 0 0 0 0 0 0 40 45 0 0 0
#> 3 0 0 0 0 0 0 0 0 47 62 23
#> 10 28 0 0 0 0 0 0 0 0 0 0
#> 11 30 0 0 0 0 0 0 0 0 0 0
#> 12 25 0 0 0 0 0 0 0 0 0 0
#> 13 0 40 0 0 0 0 0 0 0 0 0
#> 14 0 50 0 0 0 0 0 0 0 0 0
#> 15 0 0 47 0 0 0 0 0 0 0 0
#> 16 0 0 62 0 0 0 0 0 0 0 0
#> 17 0 0 23 0 0 0 0 0 0 0 0
How can I do that? I tried with the following for loop, but it was not successful as expected.
index=c(1,1,1,2,2,3,3,3)
contact=c(10,11,12,13,14,15,16,17)
age=c(28,30,25,40,50,47,62,23)
row=c(1,2,3,10,11,12,13,14,15,16,17)
col=c(1,2,3,10,11,12,13,14,15,16,17)
x=matrix(, nrow=11, ncol=11)
for (i in 1:length(row)){
for (j in 1:length(col)){
for (k in 1:length(index)){
for (m in 1:length(contact)){
if(index[k]==row[i] & contact[m]==col[j]) {x[i,j]<- age[k]}
else {x[i,j]<- 0}
print(x)
}}}}