我试图在脚本中包含使用testthat::test_that的测试,并想编写一个测试,即多个对象相等:

dfX1 = data.frame(x1 = rnorm(10),
                  x2 = rnorm(10),
                  row.names = paste0("team", 1:10))

dfX2 = data.frame(x1 = rnorm(10),
                  x2 = rnorm(10),
                  row.names = paste0("team", 1:10))

dfX3 = data.frame(x1 = rnorm(10),
                  x2 = rnorm(10),
                  row.names = paste0("team", 1:10))

# something like this?
stopifnot(all(row.names(dfX1) == row.names(dfX2) == row.names(dfX3)))


我完全知道最后一行是没有意义的。我正在寻找适合testthat语义的紧凑型解决方案。

最佳答案

尝试这个:

dfX1 = data.frame(x1 = rnorm(10),
                  x2 = rnorm(10),
                  row.names = paste0("team", 1:10))

dfX2 = data.frame(x1 = rnorm(10),
                  x2 = rnorm(10),
                  row.names = paste0("team", 1:10))

dfX3 = data.frame(x1 = rnorm(10),
                  x2 = rnorm(10),
                  row.names = paste0("team", 1:10))

# something like this?
stopifnot(identical(union(row.names(dfX1) ,row.names(dfX2)),
                row.names(dfX3)) == TRUE)


对于2个以上的向量,请使用:

stopifnot(identical(Reduce(union, list(row.names(dfX1) ,row.names(dfX2),
row.names(dfX3, ... , row.names(dfX_Nminus1))),
                row.names(dfX_N)) == TRUE)


假设所有向量的长度都相等,这也是可行的:

l.d <- list(row.names(dfX1) ,row.names(dfX2),
        row.names(dfX3))
stopifnot(length(Reduce(intersect, l.d)) == length(l.d[[1]]))

关于r - R:test_多个对象相等,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29602649/

10-12 19:16