如何在同一输出文件中合并两个不同的代码结果

时间:2017-01-02 07:09:30

标签: r output

我必须使用单个程序组合以下两个代码的结果 -

Book1 <- read.csv("Book1.csv" , header = FALSE) 
Book2 <- read.csv("Book2.csv" , header = FALSE)
Book3 <- read.csv("Book3.csv" , header = FALSE)

sink("output.txt")
for (i in seq(1,3)) {
  for (j in seq(2,5)) {
    if(Book1[i,j]==1 & Book2[i,j]==2 & Book3[i,j]==1)
      print(1) 
    else
      print(0)

   } 
}
sink()

现在,在第二个代码中,除了if Book1[i,j]==2 & Book2[i,j]==2 & Book3[i,j]==4内的条件外,其他所有内容都相同。我分别运行这两个代码并获得两个输出文本文件。如何将两个代码一起运行并在同一文本文件中获取输出。输出应该在单个文本文件中看起来像这样,开头没有任何[1] -

  0 0
  0 0 
  0 0
  0 0
  0 1 
  0 0
  0 0
  1 0
  0 0
  0 0
  0 0 
  0 0

我尝试使用连接命令,但总是出错。以下是deput() -

的结果
> dput(head(Book1))
structure(list(V1 = c(1L, 2L, 3L, 6L), V2 = c(3L, 2L, 6L, 3L), 
V3 = c(7L, 3L, 5L, 5L), V4 = c(2L, 2L, 3L, 1L), V5 = c(7L, 
1L, 4L, 1L)), .Names = c("V1", "V2", "V3", "V4", "V5"), row.names =c(NA, 4L), class = "data.frame")


> dput(head(Book2))
structure(list(V1 = c(2L, 4L, 1L, 6L), V2 = c(6L, 2L, 6L, 3L), 
V3 = c(3L, 3L, 2L, 5L), V4 = c(2L, 2L, 3L, 2L), V5 = c(7L, 
2L, 4L, 2L)), .Names = c("V1", "V2", "V3", "V4", "V5"), row.names = c(NA, 4L), class = "data.frame")

> dput(head(Book3))
structure(list(V1 = c(1L, 2L, 3L, 6L), V2 = c(3L, 4L, 6L, 3L), 
V3 = c(2L, 3L, 5L, 2L), V4 = c(2L, 2L, 6L, 1L), V5 = c(1L, 
1L, 4L, 1L)), .Names = c("V1", "V2", "V3", "V4", "V5"), row.names = c(NA, 4L), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

让我们写一个矢量化函数:

fun <- function(a, b, c) {
  #calculate the combinations of i and j values
  #and use them for vectorized subsetting
  inds <- as.matrix(expand.grid(2:5, 1:3))[, 2:1]

  #vectorized comparisons
  as.integer((Book1[inds] == a & 
              Book2[inds] == b & 
              Book3[inds] == c)) 
}

res <- cbind(fun(1, 2, 1),
             fun(2, 2, 4))

#export the result
write.table(res, "test.txt", sep = "\t", 
            row.names = FALSE,
            col.names = FALSE)
#0  0
#0  0
#0  0
#0  0
#0  1
#0  0
#0  0
#1  0
#0  0
#0  0
#0  0
#0  0