r - 如何确认两个R对象具有相同的结构?

标签 r object compare structure

我下面的测试无效。有人可以建议其他方法吗?

===不同的内容,相同的结构,需要“ true”进行比较

> x<-c(1,2,3)
> y<-x
> identical(str(x),str(y))
 num [1:3] 1 2 3
 num [1:3] 1 2 3
[1] TRUE
> y[3]<-999
> identical(str(x),str(y))
 num [1:3] 1 2 3
 num [1:3] 1 2 999
[1] TRUE
> str(x)
 num [1:3] 1 2 3
> str(y)
 num [1:3] 1 2 999
> 


但是这种方法是错误的,因为这表示x和z具有相同的结构!

> z<-list("a","b")
> identical(str(x),str(z))
 num [1:3] 1 2 3
List of 2
 $ : chr "a"
 $ : chr "b"
[1] TRUE


我正在尝试此操作,因为我需要一种方法来确认我构造的R对象具有与R包示例中提供的类型完全相同的类型。

最佳答案

自问这个问题以来已经有一段时间了,但是我一直在解决类似的问题。

提出此功能作为解决方案:

CompareStructure <-
  function(x, y) {
    # function to recursively compare a nested list of structure annotations
    # using pairwise comparisons
    TypeCompare <-
      function(xSTR, ySTR) {
        if (length(xSTR) == length(ySTR)) {
          all(mapply(
            xSTR,
            ySTR,
            FUN = function(xValue, yValue) {
              if (is.list(xValue) && is.list(yValue)) {
                all(TypeCompare(xValue, yValue))
              } else if (is.list(xValue) == is.list(yValue)) {
                identical(xValue, yValue)
              } else {
                FALSE
              }
            }
          ))
        } else {
          FALSE
        }
      }

    # if both inputs are lists
    if (is.list(x) && is.list(y)) {
      # use Rapply to recursively apply function down list
      xSTR <-
        rapply(
          x,
          f = function(values) {
            c(mode(values), length(values))
          },
          how = "list"
        )

      # use Rapply to recursively apply function down list
      ySTR <-
        rapply(
          y,
          f = function(values) {
            c(mode(values), length(values))
          },
          how = "list"
        )

      # call the compare function on both structure annotations
      return(TypeCompare(xSTR, ySTR))

    } else {
      # if inputs are not same class == automatic not same structure
      if (class(x) != class(y)) {
        FALSE
      } else {
        # get dimensions of the x input, if null get length
        xSTR <-
          if (is.null((dimsX <- dim(x)))) {
            length(x)
          } else {
            dimsX
          }

        # get dimensions of the y input, if null get length
        ySTR <-
          if (is.null((dimsY <- dim(y)))) {
            length(y)
          } else {
            dimsY
          }

        # call the compare function on both structure annotations
        return(TypeCompare(xSTR, ySTR))
      }
    }
  }


比较嵌套列表中元素的模式和长度以及无列表对象的类和维

关于r - 如何确认两个R对象具有相同的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32399843/

相关文章:

r - 查找小于特定值的向量中的最大数

r - 使用 gc() 命令强制在 R 中运行垃圾回收

swift - 在基于 swift 的应用程序中与枚举成员交互

Java:命中检测未正确检测两个对象之间的重叠

php - 查看数组中是否存在文本区域值

JavaScript - 过滤掉数组中相似的字符串

matlab - 检查单元格内的成员

r - 如何在 CRAN 上提交时删除 PackRat 文件夹

r - 整洁评估 : Evaluation of quosure in function within map

使用相同覆盖变量的 javascript 对象