Reputation:
I have to combine the results of following two codes using a single program -
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()
Now, in the second code everything else is same except the condition inside if
which is Book1[i,j]==2 & Book2[i,j]==2 & Book3[i,j]==4
. I am running these two codes separately and getting two output text files. How can I run the two codes together and get the output in the same text file. The output should be looking like this in a single text file without any [1]
in the beginning -
0 0
0 0
0 0
0 0
0 1
0 0
0 0
1 0
0 0
0 0
0 0
0 0
I tried using concatenation command but always got an error. And here is the result for 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")
Upvotes: 0
Views: 351
Reputation: 132706
Let's write a vectorized function:
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
Upvotes: 2