我喜欢这个数字为-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
...
每一行都是客户的答案,其中1 - 是推荐的,-1 - 不推荐,0 - 不重要。
我需要将对上的每一行分开,其中1 - 最佳答案和-1 - 最差答案(1最佳0,0最佳-1),如下表所示。
算法:
在第1行需要将第1个数字与第2个数字进行比较。如果数字相同,则需要与下一个数字进行比较 - 第1个和第3个。
资源1 下,1, 0 中,1,1,1,1
如果1st first 3rd,则在结果表中写一个新行,其中第一个数字为' 1',3rd - ' -1'和所有其他 - ' 0'。
结果1 中,0, -1 中,0,0,0,0
然后需要将第一个数字与下一个数字进行比较 - 第四个等等
如何在 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
答案 0 :(得分:0)
好的,有点笨拙的解决方案。我首先生成我将比较的索引,并使用Map
循环这两个索引向量。以第一行为例:
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
这是第一行。对于整个数据框df
:
lst = lapply(1:nrow(df), function(i){
do.call(rbind, Map(Curry(f, x=unlist(df[i,])), first, last))
})
do.call(rbind, lst)