0

how do i build a function in R with a single vector that ranks the vector where and returns a n x n matrix where it returns 1 if i is preferred over j otherwise it returns 0.
I so far have this..

preferences <- matrix(nrow = n,ncol = n)

convert <- function(n){
for (i in 1:length(n)){
  for (j in 1:length(n)){

## If ith element < jth element then TRUE
 if (preferences[i,j] <- preferences[i] < preferences[j]){
  1
   }else if (preferences[i]==preferences[j]){
  0 
   } else{
  0}
}
}
print(preferences[i,j])
}
convert(c(8,1,3))
Timmy N.
  • 1
  • 1
  • 1
    Please provide a small [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) example along with the expected output. – Ronak Shah Nov 10 '16 at 04:10

3 Answers3

1

This can be easily done with outer

 +(outer(v1, v1, FUN= '<'))

If we need to create the diagonal elements, one option is

m1 <- matrix(0, length(n), length(n))
m1[col(m1)==row(m1)] <- n
m1
#     [,1] [,2] [,3]
#[1,]    8    0    0
#[2,]    0    1    0
#[3,]    0    0    3

data

set.seed(24)
v1 <- sample(1:7, 10, replace=TRUE)
n <- c(8,1,3)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Maybe you need diag

n=c(8,1,3) 
diag(n, length(n), length(n))

#     [,1] [,2] [,3]
#[1,]    8    0    0
#[2,]    0    1    0
#[3,]    0    0    3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

This will also work:

vec <- c(8,1,3)
outer(vec, vec, function(x,y){ifelse(x==y, x, 0)})
    [,1] [,2] [,3]
[1,]    8    0    0
[2,]    0    1    0
[3,]    0    0    3
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63