如何在R中的Repeat循环中写入文件

时间:2014-12-23 15:41:07

标签: r

我有六个文件,在一个以ascii文件分隔的空格中包含600万个条目。我使用maptools包读取ascii文件(read.ascii)。每个文件代表图像中的一个像素。我需要对每个单独的像素实体求和(表1中的数据点1 +数据点1表2 + .... +数据点1表6)。我已经创建了一个程序,可以拉动和求和图像中的第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
 }
}

1 个答案:

答案 0 :(得分:0)

我没有对此进行测试,因为您没有提供示例数据,但我认为您可以大大简化和缩短代码。在这个版本中,你摆脱了重复循环,先做所有的总和,然后只写一次文件。

# 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,这简化了一些事情。

相关问题