Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对R中的数据帧行执行按位AND或类似操作?_R_Vector_Bit Manipulation_Dataframe_Operation - Fatal编程技术网

对R中的数据帧行执行按位AND或类似操作?

对R中的数据帧行执行按位AND或类似操作?,r,vector,bit-manipulation,dataframe,operation,R,Vector,Bit Manipulation,Dataframe,Operation,我有两个数据帧A和B,两个维度都相同。不能保证行和列标签在帧之间的顺序相同 两个帧都包含值0和1,其中1表示帧的行和列之间存在定向“边”(相应地,0表示没有连接) 我想找到两个框架的共同点。换句话说,我想要一个与a和B尺寸相同的数据帧,它们包含1值,其中a和B的行和列都有1 目前,我正在遍历行和列,并测试它们是否都是1 这是可行的,但我想有一种更有效的方法。有没有一种方法可以对数据帧的行向量执行与“按位AND”操作等效的操作,即返回一个可以填充回新数据帧的行向量?还是有其他更聪明(更有效)的方法

我有两个数据帧
A
B
,两个维度都相同。不能保证行和列标签在帧之间的顺序相同

两个帧都包含值
0
1
,其中
1
表示帧的行和列之间存在定向“边”(相应地,
0
表示没有连接)

我想找到两个框架的共同点。换句话说,我想要一个与
a
B
尺寸相同的数据帧,它们包含
1
值,其中
a
B
的行和列都有
1

目前,我正在遍历行和列,并测试它们是否都是
1

这是可行的,但我想有一种更有效的方法。有没有一种方法可以对数据帧的行向量执行与“按位AND”操作等效的操作,即返回一个可以填充回新数据帧的行向量?还是有其他更聪明(更有效)的方法

编辑

矩阵乘法比我最初的方法快得多。分类是实现这一目标的关键

findCommonEdges <- function(edgesList) {
    edgesCount <- length(edgesList)
    print("finding common edges...")
    for (edgesIdx in 1:edgesCount) {
        print(paste("...searching against frame", edgesIdx, sep=" "))
        edges <- edgesList[[edgesIdx]]
        if (edgesIdx == 1) {
            # define commonEdges data frame as copy of first frame
            commonEdges <- edges
            next
        }
        #
        # we reorder edge data frame row and column labels 
        # to do matrix multiplication and find common edges
        #
        edges <- edges[order(rownames(commonEdges)), order(colnames(commonEdges))]
        commonEdges <- commonEdges * edges
    }
    commonEdges
}

findCommonEdges可能是这样的

df1 <- as.data.frame(matrix(sample(0:1,25,replace = TRUE),5,5))
df2 <- as.data.frame(matrix(sample(0:1,25,replace = TRUE),5,5))
df3 <- matrix(0,5,5)
df3[df1 == 1 & df2 == 1] <- 1
> df3
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    1    1
[3,]    1    1    1    0    0
[4,]    0    1    0    0    0
[5,]    0    0    0    0    0

df1您可以使用正常乘法

您还可以使用逻辑&运算符,这是您要查找的“按位and”。您的表达式将看起来像
(a&b)+0
+0
将从布尔值转换回整数)


注意:对于数据帧,它的工作方式完全相同。

谢谢,@joran:-)这个例子表明R是一种非常优雅的语言,我喜欢欣赏它的优雅:-)谢谢,这很有道理,我只需要以相同的方式排列两个帧,这样结果就正确了。注意,你不应该把
&
与“按位和”混淆操作符
&
与C一样。你可以从
bitops
包中得到它,它的函数是
bitAnd()
@Sacha,是的,我们应该说“elementwise”而不是“bitwise”,这是正确的,但我认为我们通过OP相互理解……是的,这更多的是指人们随意搜索“bitwise and in R”或者其他什么东西,而不是阅读整个帖子:)
// generate data
a = matrix(rbinom(100, 1, 0.5), nrow = 10)
b = matrix(rbinom(100, 1, 0.5), nrow = 10)

a * b // this is the result!