簡體   English   中英

如何在R中的重復循環中寫入文件

[英]How to write to file in Repeat loop in R

我有六個文件,這些文件在以空格分隔的ascii文件中包含600萬個條目。 我正在使用maptools包讀取ascii文件(read.ascii)。 每個文件代表圖像中的一個像素。 我需要總結每個像素實體(表1中的數據點1 +表2中的數據點1 + .... +表1中的數據點1)。 我創建了一個程序,可以提取和求和圖像中的第i個像素。 但是,我在弄清楚如何將這些匯總寫入一個ascii文件時遇到問題。 有任何想法嗎?

我的代碼:

library(maptools)

#Variable Declaration
num <- 6210775
i <- 1
#Open the 6 Factor files
tablex <- data.frame(readAsciiGrid("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_01.asc"))
tabley <- data.frame(readAsciiGrid("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_02.asc"))
tablez <- data.frame(readAsciiGrid("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_03.asc"))
tablea <- data.frame(readAsciiGrid("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_04.asc"))
tableb <- data.frame(readAsciiGrid("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_05.asc"))
tabled <- data.frame(readAsciiGrid("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_06.asc"))

repeat{
#Variable declaration for position within data frame
x <- tablex[i,1]

y <- tabley[i,1]

z <- tablez[i,1]

a <- tablea[i,1]

b <- tableb[i,1]

d <- tabled[i,1]

#Adding up ALL six factors
ALL <- x+y+z+a+b+d
#Write to file--This is my issue...
print(ALL)
#Iterative variable
i=i+1
#Condition to break if i is GT the number of preset lines
if(i > num){
  break
 }
}

由於您沒有提供示例數據,因此我沒有對此進行測試,但是我認為您可以大大簡化和縮短代碼。 在此版本中,您擺脫了重復循環,首先進行所有求和,然后僅一次寫入文件。

# Read the 6 factor files and store them in a list
tables = lapply(1:6, function(x) {
  readAsciiGrid(paste0("E:/KOC/Satellite/Daytime/PCA_R_CART/PSPP_PCA_0", x, ".asc"))
})

# Instead of hard-coding num, you can also do, for example: num=nrow(tables[[1]])
num = 6210775

# Function to sum one set of values
oneSum = function(row) {
    sum(sapply(1:length(tables), function(x) {
          tables[[x]][row,1]
    }))
 }

# Run the oneSum function on every row of the ascii grids and store the results
# in allSums
allSums = sapply(1:num, oneSum)

# Write the data to a file
write.table(allSums, file="output.file.txt")

更新:我將代碼更改為使用sapply而不是lapply ,這簡化了一些事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM