如何根据 r 中 table 的值创建一个真值 table

How to create a truth table based on table of values in r

我正在尝试创建一个脚本,该脚本将根据不同的值创建一个事实 table。

例子

事实table 是

我是 r 的新手。我知道它在数据分析方面有很多强大的功能,但这会很有帮助。正在寻找可能用稀疏矩阵实现的东西,但我不知道。

下次请在问题中包含数据,避免放图片。

可能是这样使用 data.table:

数据:

library('data.table')
df1 <- data.table(Name = c('Bob', 'Bob', 'Luke'),
                  Location = c('Texas', 'Ohio', 'Utah'),
                  Pet = c('Dog', 'Cat', 'Dog'),
                  Coder = c(1,0,1),
                  stringsAsFactors = FALSE )

代码:

df1[, id := .I ] # assign unique id, and later it will be removed
select_cols <- c('Name', 'Location', 'Pet') # selected columns
dcast( data = melt(df1, measure.vars = select_cols ),  
       formula = "id + Coder ~ value", 
       fun.aggregate = length, 
       fill = 0  )[, id := NULL ][]

#    Coder Bob Cat Dog Luke Ohio Texas Utah
# 1:     1   1   0   1    0    0     1    0
# 2:     0   1   1   0    0    1     0    0
# 3:     1   0   0   1    1    0     0    1