应用蒙版并创建均值向量的循环 [英] Loop for applying mask and creating a vector of means

查看:55
本文介绍了应用蒙版并创建均值向量的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多个文本文件上应用掩码后创建均值向量(1,408).每个文件对应一个变量&年份为1950-2013年,因此该变量有64个文件,并且有22个变量.这是我在R中应用的编码:

I want to create a vector of means after applying a mask to a number of text files (1,408). Each file corresponding to a variable & year from 1950-2013, so 64 files for that variable and there are 22 variables. this is the coding I applied in R:

dataDir <- "C:\\dir\\"
patternC <-"Var1_"
filesSizeC = sort(list.files(dataDir,patternC))

  for (i in 1:length(filesSizeC)) {
   theData<-read.table(paste(dataDir,filesSizeC[i],sep=""),header=F,sep=",")
}

mask <- read.csv("http://dl.dropbox.com/s/2tbffe65i53afj1/examplemask.txt",
header=F)

product <- mask * theData
product[product == 0] <- NA
mean(product$V1, na.rm=TRUE)

对于64个文本文件,这仅给我一个值,即平均值.但是我希望在应用蒙版后每个文本文件的均值.我对此进行了修改,以尝试为我提供每年的均值向量:

This only gives me one value, the mean, for the 64 text files. But I want the mean for each text file after the masking has been applied. I amended the coding to this, to try and give me a vector of means for each year:

for (i in 1:length(filesSizeC)) {
theData<-read.table(paste(dataDir,filesSizeC[i],sep=""),header=F,sep="\t")  
pdt <- mask*theData

if (i>0) {
    theMeanValues <- c(theMeanValues,mean(pdt))

  } else {
  theMeanValues <- c(mean(pdt))
 }
}

错误消息是:

Error: object 'theMeanValues' not found

我不太确定如何根据自己的需要更改此内容.

I'm not too sure how to change this for what I want.

所以本质上我想实现这一目标:

So essentially I want to achieve this:

year | Var1_Masked_Mean | Var2_Masked_Mean | etc...
1950
1951
 .
 .
 .
2013

我希望我的要求是有道理的!

I hope what I'm asking makes sense!

谢谢

推荐答案

在您的示例中,R的索引是 1 而不是 0 ...

R is indexed at 1 not 0 in your example...

for (i in 1:length(filesSizeC)) {

所以改变这个

if (i>0) {
  ...
  }

if (i>1) {
  ...
  }

在循环的第一次迭代中,当 i == 1 时,您将创建 theMeanValues 变量.

And in the first iteration of the loop when i==1 you will create the theMeanValues variable.

这篇关于应用蒙版并创建均值向量的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆