检查2个R程序是否相同

Mar*_*ler 5 r

最近我了解到我可以使用identicalall.equal检查2个数据集是否相同.

我还可以用它们来检查2个R程序是否相同吗?有比下面更好或更合适的方式吗?

program.1 <- readLines("c:/r stuff/test program 1.r")
program.2 <- readLines("c:/r stuff/test program 2.r")

identical(program.1, program.2)
all.equal(program.1, program.2)
isTRUE(all.equal(program.1, program.2))
Run Code Online (Sandbox Code Playgroud)

感谢您的任何想法或建议.

以下是比较的2个测试程序的内容:

a <- matrix(2, nrow=3, ncol=4)

b <- c(1,2,3,4,5,6,7,8,6,5,4,3,2)

table(b)

c <- runif(2,0,1)

a * b
Run Code Online (Sandbox Code Playgroud)

#2012年3月编辑从这里开始#

下面是一个小例子程序使下述收益约什的功能FALSE,而identicalall.equal回报TRUE.我将两个程序文件命名为'testa.r'和'testb.r'.

set.seed(123)

y <- rep(NA, 10)

s <- matrix(ceiling(runif(10,0,100)), nrow=10, byrow=T)

a   <- 25
ab  <- 50
abc <- 75

for(i in 1:10) {
     if(s[i] >  a  & s[i] <= ab ) y[i] = 1
     if(s[i] >  ab & s[i] <= abc) y[i] = 2
}

s
y
Run Code Online (Sandbox Code Playgroud)

这是我用来读取包含上述代码的两个文件的R程序.

program.1 <- readLines("c:/users/Mark W Miller/simple R programs/testa.r")

program.2 <- readLines("c:/users/Mark W Miller/simple R programs/testb.r")


identical(program.1, program.2)
all.equal(program.1, program.2)
isTRUE(all.equal(program.1, program.2))


parseToSame <- function(file1, file2) {
    a <- parse(file = file1)
    b <- parse(file = file2)
    attributes(a) <- NULL
    attributes(b) <- NULL
    identical(a,b)
}

parseToSame(

     "c:/users/Mark W Miller/simple R programs/testa.r",
     "c:/users/Mark W Miller/simple R programs/testb.r"

)
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 8

这是一个可能稍微有用的函数,因为它测试两个文件是否解析为同一个表达式树.(因此,即使它们具有不同的格式,附加的空行和空格等,它们也会在两个文件中找到相同的代码,只要它们解析为同一个对象.)

parseToSame <- function(file1, file2) {
    a <- parse(file = file1)
    b <- parse(file = file2)
    attributes(a) <- NULL
    attributes(b) <- NULL
    identical(a,b)
}
Run Code Online (Sandbox Code Playgroud)

以下是该功能的演示:

# Create two files with same code but different formatting
tmp1 <- tempfile()
tmp2 <- tempfile()
cat("a <- 4; b <- 11; a*b \n", file = tmp1)
cat("a<-4

     b    <-    11 
     a*b \n", file = tmp2)

# Test out the two approaches
identical(readLines(tmp1), readLines(tmp2))
# [1] FALSE
parseToSame(tmp1, tmp2)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)


Rei*_*son 3

是的你可以。但它们可能不够灵活,无法满足您的需求。program.1并且program.2必须完全相等,在相同的行上具有相同的代码等。不允许偏移。diff@Jack Maney在上面的评论中提到。这允许在可能被 1 条或多条线偏移的相同线中具有更大的灵活性。请注意,他指的是标准diff实用程序而不是 R 函数diff()

两者需要完全相等的原因是readLines()读取文件的行作为字符(字符串)向量:

> con <- textConnection("foo bar foo\nbar foo bar")
> foo <- readLines(con)
> close(con)
> str(foo)
 chr [1:2] "foo bar foo" "bar foo bar"
Run Code Online (Sandbox Code Playgroud)

当使用identical()and时all.equal(),它们会将 的元素 1program.1与 的元素 1进行比较program.2,依此类推所有元素(行)。即使代码相同但包含额外的回车符,例如identical()all.equal()都会返回FALSE,因为两个字符向量的元素在任何意义上都不相等。