algorithm - Separation data on the pairs in R -
i have table numbers -1, 0 , 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 answer of customers 1 - recommend, -1 - not recommend , 0 - doesn't matter.
i need separate each row on pairs, 1 - best answer , -1 - worst answer (1 best 0, 0 best -1) in table below.
algorithm:
in 1st row need compare 1st number 2nd. if numbers same, need compare next number - 1st 3rd.
source
1,1,0,1,1,1,1
if 1st better 3rd, write new row result table 1st number '1', 3rd - '-1' , other - '0'.
result
1,0,-1,0,0,0,0
then need compare 1st number next - 4th , etc.
- when 1st number compared other numbers, need compare 2nd number 3rd, 4th , others.
- when numbers of 1st row compared between each other, need switch next row.
how 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
ok, little clumsy solution. generate first indexes on compare , loop on these 2 indexes vectors using map
. first line 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 first line. 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)
Comments
Post a Comment