-1

I have like this table with numbers -1, 0 and 1.

Innovation,Licensing,Marketing,Portfolio,Purchase,Quality,Support
1,1,0,1,1,1,1
0,-1,-1,-1,0,1,1
1,1,1,1,1,1,1
-1,0,0,1,-1,1,0
...

Each row is an answer of customers where 1 - is recommend, -1 - not recommend and 0 - doesn't matter.

I need to separate each row on the pairs, where 1 - best answer and -1 - worst answer (1 best 0, 0 best -1) like in table below.

Algorithm:

  1. In the 1st row need to compare 1st number with 2nd. If numbers the same, need to compare with next number - 1st with 3rd.

    Source

    1,1,0,1,1,1,1

  2. If 1st better 3rd, then write a new row to the result table where 1st number will be '1', 3rd - '-1' and all other - '0'.

    Result

    1,0,-1,0,0,0,0

  3. Then need to compare 1st number with next - 4th and etc.

  4. When 1st number will be compared with all other numbers, need to compare 2nd number with 3rd, then with 4th and others.
  5. When all numbers of 1st row will be compared between each other, need to switch to next row.

How to do this in R?

Innovation,Licensing,Marketing,Portfolio,Purchase,Quality,Support
1,0,-1,0,0,0,0
0,1,-1,0,0,0,0
0,0,-1,1,0,0,0
0,0,-1,0,1,0,0
0,0,-1,0,0,1,0
0,0,-1,0,0,0,1
1,-1,0,0,0,0,0
1,0,-1,0,0,0,0
1,0,0,-1,0,0,0
-1,0,0,0,0,1,0
-1,0,0,0,0,0,1
0,-1,0,0,1,0,0
0,-1,0,0,0,1,0
0,-1,0,0,0,0,1
0,0,-1,0,1,0,0
0,0,-1,0,0,1,0
0,0,-1,0,0,0,1
0,0,0,-1,1,0,0
0,0,0,-1,0,1,0
0,0,0,-1,0,0,1
0,0,0,0,-1,1,0
0,0,0,0,-1,0,1
-1,1,0,0,0,0,0
-1,0,1,0,0,0,0
-1,0,0,1,0,0,0
-1,0,0,0,0,1,0
-1,0,0,0,0,0,1
0,-1,0,1,0,0,0
0,1,0,0,-1,0,0
0,-1,0,0,0,1,0
0,0,-1,1,0,0,0
0,0,1,0,-1,0,0
0,0,-1,0,0,1,0
0,0,0,1,-1,0,0
0,0,0,1,0,0,-1
0,0,0,0,-1,1,0
0,0,0,0,-1,0,1
0,0,0,0,0,1,-1
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

Ok, a little clumsy solution. I generate first the indexes on which I will compare and loop over these two indexes vectors using Map. For the first line for example:

library(functional)

x     = unlist(df[1,])
first = rep(1:6,6:1)
last  = sequence(6:1) + first

f = function(x, u, v)
{
    s = sign(x[u]-x[v])
    if(s!=0)
    {
        y = rep(0, length(x))
        y[u] = s
        y[v] = -1*s
        return(y)
    }
}

do.call(rbind, Map(Curry(f, x=x), first, last))

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#[1,]    1    0   -1    0    0    0    0
#[2,]    0    1   -1    0    0    0    0
#[3,]    0    0   -1    1    0    0    0
#[4,]    0    0   -1    0    1    0    0
#[5,]    0    0   -1    0    0    1    0
#[6,]    0    0   -1    0    0    0    1

This was for the first line. For the whole dataframe df:

lst = lapply(1:nrow(df), function(i){
    do.call(rbind, Map(Curry(f, x=unlist(df[i,])), first, last))
}) 

do.call(rbind, lst)
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87