如何将循环的结果写入R中的csv文件中?

时间:2018-10-17 15:59:25

标签: r

我正在尝试运行此脚本:

input <- read.csv ("trio.csv")

for (i in 1:nrow(input)) {
  if (input[i, 6] == input[i, 2]) {
    if (input[i, 7] == input[i, 4] |
        input[i, 7] == input[i, 7]) {
      print ("h1")
    } else {
      print ("not h1")
    }
  } else if (input[i, 6] == input[i, 3]) {
    if (input[i, 7] == input[i, 4] | input[i, 7] == input[i, 7]) {
      print ("h1")
    } else {
      print ("not h1")
    }
  } else {
    print("not h1")
  }
}

for (j in 1:nrow(input)) {
  if (input[j, 7] == input[j, 2]) {
    if (input[j, 6] == input[j, 4] | input[j, 6] == input[j, 7]) {
      print ("h2")
    } else {
      print ("not h2")
    }
  } else if (input[j, 7] == input[j, 3]) {
    if (input[j, 6] == input[j, 4] |input[j, 6] == input[j, 7]) {
      print ("h2")
    } else {
      print ("not h2")
    }
  } else {
    print("not h2")
  }
}

trio.csv文件由7列和100行组成,下面是trio.csv的示例:

dput(head(input))

structure(list(familyID = c(1001L, 1004L), Pat1 = structure(2:1, .Label = 
c("REF", "X1"), class = "factor"), Pat2 = structure(1:2, .Label = c("C2", 
"REF"), class = "factor"), Mat1 = structure(1:2, .Label = c("C2", 
"REF"), class = "factor"), Mat2 = structure(c(1L, 1L), .Label = "C2", 
class  = "factor"), 
Ch1 = structure(2:1, .Label = c("REF", "X1"), class = "factor"), 
Ch2 = structure(1:2, .Label = c("C2", "REF"), class = "factor")), 
row.names = 1:2, class = "data.frame") 

如何将第一个循环和第二个循环的结果保存在新文件的两个不同列中?

1 个答案:

答案 0 :(得分:0)

这是我设法将两个循环的结果保存到两个新的csv文件中的方法,它对我有用。欢迎提出所有提高效率的建议。谢谢

input <- read.csv ("trio.csv")

b <- matrix( , 0,ncol=2, )
d <- matrix( , 0,ncol=2, )

for (i in 1:nrow(input)) {
  x= if (input[i, 6] == input[i, 2]) {
    if (input[i, 7] == input[i, 4] |
        input[i, 7] == input[i, 5]) {
      print ("h1")
    } else {
      print ("not h1")
    }
  } else if (input[i, 6] == input[i, 3]) {
    if (input[i, 7] == input[i, 4] | input[i, 7] == input[i, 5]) {
      print ("h1")
    } else {
      print ("not h1")
    }
  } else {
    print("not h1")
  } 
    b <- rbind(b,c(i, x))
}

for (j in 1:nrow(input)) {
  y= if (input[j, 7] == input[j, 2]) {
    if (input[j, 6] == input[j, 4] | input[j, 6] == input[j, 5]) {
      print ("h2")
    } else {
      print ("not h2")
    }
  } else if (input[j, 7] == input[j, 3]) {
    if (input[j, 6] == input[j, 4] |input[j, 6] == input[j, 5]) {
      print ("h2")
    } else {
      print ("not h2")
    }
  } else {
    print("not h2")
  } 
    d<- rbind(d, c(j, y))
}


write.table(b,"hyp1.csv",sep=",",row.names = FALSE,col.names = FALSE)
write.table(d,"hyp2.csv",sep=",",row.names = FALSE,col.names = FALSE)