R将二进制列转换成条件

时间:2018-11-18 15:11:28

标签: r dataframe matrix binary conditional-statements

我想知道是否有任何简单的r函数可以将二进制列转换为有条件的方阵?

我有以下源数据框:

enter image description here

structure(list(SHOES = c(0,0,0,0,0,0,0,0,0),  
               LEATHER = c(0,0,0,0,0,0,0,0,0), 
               SPORTSWEAR = c(1,1,1,0,0,0,1,0,0), 
               SHIRTS = c(1,0,1,0,0,0,0,0,0), 
               SUITS = c(0,0,1,0,0,0,0,0,1)), 
          .Names = c("SHOES", "LEATHER", "SPORTSWEAR", "SHIRTS", "SUITS"), 
          class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L))

我希望得到的结果如下(条件:基于源数据帧,如果两列都为1,则计为1),然后合计计数。

示例1:运动服和衬衫出现2次(均等于1),因此合计计数为2,其他保持为0。

示例2:衬衫和服装出现1次(均等于1),因此合计计数为1,其他计数保持为0。

enter image description here

1 个答案:

答案 0 :(得分:2)

m = sapply(df1, function(x) sapply(df1, function(y) sum(x*y)))
replace(m, !lower.tri(m), 0)
#           SHOES LEATHER SPORTSWEAR SHIRTS SUITS
#SHOES          0       0          0      0     0
#LEATHER        0       0          0      0     0
#SPORTSWEAR     0       0          0      0     0
#SHIRTS         0       0          2      0     0
#SUITS          0       0          1      1     0

数据

df1 = structure(list(SHOES = c(0, 0, 0, 0, 0, 0, 0, 0, 0), LEATHER = c(0, 
0, 0, 0, 0, 0, 0, 0, 0), SPORTSWEAR = c(1, 1, 1, 0, 0, 0, 1, 
0, 0), SHIRTS = c(1, 0, 1, 0, 0, 0, 0, 0, 0), SUITS = c(0, 0, 
1, 0, 0, 0, 0, 0, 1)), class = "data.frame", row.names = c(NA, 
-9L))