【问题标题】:How to merge two different code results in R in the same output file如何在同一个输出文件中合并两个不同的代码导致 R
【发布时间】:2017-01-02 07:09:30
【问题描述】:

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

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 &amp; Book2[i,j]==2 &amp; 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

我尝试使用 concatenation 命令,但总是出错。这是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")

【问题讨论】:

  • 请同时提供输入数据。您可以refer here 寻求指导。此外,您似乎希望输出按列连接。是这样吗?
  • @Aramis7d 是的,很抱歉,但链接会将我引导至“未找到页面”页面。
  • 你能看看cbind()吗?将所有书籍组合在一起
  • @Dark_Knight 很奇怪。试试stackoverflow.com/help/mcve。另外,您是否确信所有单独的输出都具有相同的长度?
  • @Aramis7d 是的,所有单独的输出都具有相同的长度。循环运行的次数相等。每个代码的时间。

标签: r output


【解决方案1】:

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

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

【讨论】:

  • [, 2:1] 是做什么的?
  • 学习help("[")。它切换列。
猜你喜欢
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 2023-02-01
  • 2013-10-17
  • 2017-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多