[英]how to write the outcome of a loop into csv file in 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")
如何將第一個和第二個循環的結果保存在新文件的兩個不同列中?
這就是我設法將兩個循環的結果保存到兩個新的 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.