我正在编写R代码来生成1个堆叠的文本文件,我将在单独的地球化学建模软件中运行。为此,我从另一个文本文件中提取数据,其中文件的每一行都是不同的样本。而不是制作单独的文本文件,我想制作一个完整的文本文件,基本上我在每个样本输出的rbind()。到目前为止,我有代码循环遍历单个文本文件,但是如何创建一个文本文件而不必重新导入我已经创建的所有文件。重新导入不是一个好的选择,因为下面的R.代码不容易阅读。谢谢
set.seed(12)
data <- matrix(sample(12*15), nrow = 12, ncol = 15)
out <- (matrix(nrow=5, ncol=1))
for (i in 1: nrow(data)) {
out[1,1] <- paste('SOLUTION 00', rownames(data[i,]), " ", data[i,1], sep="")
out[2,1] <- paste("temp 21")
out[3,1] <- paste("pH"," ", ((data[i,2]) - 7) / ((-1) / (((25 + 273.15)
/ 298) * 59)) * ((-1) / (((21 + 273.15) / 298) * 59)) + 7, sep = "")
out[4,1] <- paste("units umol/L")
out[5,1] <- paste("Cl", " ", data[i,3], sep="")
file.name <- paste("00",rownames(data[i,]), "_", data[i,1], ".txt", sep="")
write.table(out, file=filename, sep="", row.names=FALSE, col.names=FALSE, na=" ", quote=FALSE)
} # At this point, how do I make one giant text file, not individual text files?
答案 0 :(得分:0)
你在循环中写作。如果将其移出循环,它将生成一个文本文件。
set.seed(12)
data <- matrix(sample(12*15), nrow = 12, ncol = 15)
out <- (matrix(nrow=5, ncol=1))
for (i in 1: nrow(data)) {
out[1,1] <- paste('SOLUTION 00', rownames(data[i,]), " ", data[i,1], sep="")
out[2,1] <- paste("temp 21")
out[3,1] <- paste("pH"," ", ((data[i,2]) - 7) / ((-1) / (((25 + 273.15)
/ 298) * 59)) * ((-1) / (((21 + 273.15) / 298) * 59)) + 7, sep = "")
out[4,1] <- paste("units umol/L")
out[5,1] <- paste("Cl", " ", data[i,3], sep="")
}
file.name <- paste("00",rownames(data[i,]), "_", data[i,1], ".txt", sep="")
write.table(out, file=file.name, sep="", row.names=FALSE, col.names=FALSE, na=" ", quote=FALSE)
答案 1 :(得分:0)
您可以设置输出矩阵out
,以便存储所有结果。它只需要考虑如何设置索引:
# 5 rows in out for each row of data
out <- (matrix(nrow=5 * nrow(data), ncol=1))
for (i in 1:nrow(data)) {
# Start at 1 for i = 1, 6 for i = 2, etc.
first_row = 5 * (i - 1) + 1
out[first_row, 1] <- paste('SOLUTION 00', rownames(data[i,]), " ", data[i,1], sep="")
out[first_row + 1, 1] <- paste("temp 21")
out[first_row + 2, 1] <- paste("pH"," ", ((data[i,2]) - 7) / ((-1) / (((25 + 273.15)
/ 298) * 59)) * ((-1) / (((21 + 273.15) / 298) * 59)) + 7, sep = "")
out[first_row + 3,1] <- paste("units umol/L")
out[first_row + 4,1] <- paste("Cl", " ", data[i,3], sep="")
}
# Write all results at once
write.table(out, file="AllRecords.txt", sep="", row.names=FALSE, col.names=FALSE, na=" ", quote=FALSE)