2017-07-03 42 views
1

我有以下的二元数据集:总和的二进数据结构的条件下,相同的价值观

ID.x  Attribute1.x  Attribute2.x ID.y  Attribute1.y Attribute2.y rowsum 
2323  11    11   9923  22   11  1 
3423  11    22   3422  11   44  1 
5343  22    22   5555  11   0  0 
54336  0     44   0234  11   44   1 
4334  11    22   2345  44   11   1 
34563  22    0   9429  0    22   2 
34534  44    0   2345  44   11  1 

我要检查,如果从参与者X的每一列的属性是相同的Y的

Attribute1.x == Attribute1.y 
Attribute2.x == Attribute2.y 
... 

并将它们加总成“rowsum”列。我的完整数据框由每个actor(x,y)的100个Attributes列组成。

我已经尝试过,莫名其妙地失败:

dyadic_df$rowsome <- apply(dat_wp_dyadic_1, 1, function(x) length(which(x==11 & x==22 & x==0 & x==44))) 

回答

2

获取列的索引时得到内相同相交lenght适用

# get index 
x_index <- grep("^A.*x$", colnames(df1)) 
y_index <- grep("^A.*y$", colnames(df1)) 

# loop by row, sort and compare 
df1$myRowSum <- 
    apply(df1, 1, function(i){ 
    length(intersect(i[x_index], i[y_index])) 
    }) 

df1 
# ID.x Attribute1.x Attribute2.x ID.y Attribute1.y Attribute2.y rowsum myRowSum 
# 1 2323   11   11 9923   22   11  1  1 
# 2 3423   11   22 3422   11   44  1  1 
# 3 5343   22   22 5555   11   0  0  0 
# 4 54336   0   44 234   11   44  1  1 
# 5 4334   11   22 2345   44   11  1  1 
# 6 34563   22   0 9429   0   22  2  2 
# 7 34534   44   0 2345   44   11  1  1 

编辑:

OP:根据你的建议我用sum((i [x_index] == i [y_index]))而不是相交来总结每列有多少个值是完全相同的。现在,我想总结一下,如果条件满足之和(I [x_index] &我[x_index] == 11 | 22)

mySet <- c(11, 22) 

# loop by row, sort and compare 
df1$myRowSumFilter <- 
    apply(df1, 1, function(i){ 
    length(intersect(i[x_index][ i[x_index] %in% mySet ], 
        i[y_index][ i[y_index] %in% mySet ])) 
    }) 

df1 
+0

非常感谢您!还有一个问题:根据你的建议,我用sum((i [x_index] == i [y_index]))而不是相交来总结每列有多少个值是完全相同的。现在我想总结一下条件是否满足sum(i [x_index]&i [x_index] == 11 | 22)...但是我得到一个错误?! – PeteWoods

+0

@PeteWoods你可以只保留'11,22'的矢量然后检查。我会用一个例子来更新。 – zx8754

+1

@PeteWoods后更新了一个例子,今后避免在评论中提出新的问题。 – zx8754