R for循环错误消息

时间:2015-07-13 12:44:02

标签: r for-loop

我一直在尝试在我的data.frame上运行for循环,我无法弄清楚问题是我的代码还是数据的类结构。以下是一小部分数据:

dafr.t <- structure(list(`1976` = c(17.134, 18.668, 27.342, 21.277), `1977` = c(13.83, 15.177, 21.334, 13.683), `1978` = c(8.739, 10.468, 14.756, 12.529), `1979` = c(7.669, 9.824, 9.817, 11.423), `1980` = c(10.448, 13.157, 12.346, 12.51), `1981` = c(11.382, 15.327, 17.412, 13.535), `1982` = c(7.734, 13.174, 16.069, 10.495), `1983` = c(8.064, 11.492, 13.757, 8.201), `1984` = c(7.334, 11.885, 16.349, 9.725), `1985` = c(11.752, 14.943, 20.25, 14.998), `1986` = c(15.779, 14.853, 22.28, 16.67), `1987` = c(10.974, 8.711, 14.813, 12.586), `1988` = c(10.951, 13.416, 15.838, 11.068), `1989` = c(15.258, 18.988, 19.15, 14.534), `1990` = c(15.81, 14.642, 19.728, 14.286), `1991` = c(11.65, 11.972, 20.312, 12.452), `1992` = c(13.799, 12.269, 20.244, 12.652), `1993` = c(13.286, 11.219, 13.549, 9.257), `1994` = c(15.701, 11.622, 14.089, 6.603), `1995` = c(12.556, 12.94, 15.634, 9.451), `1996` = c(13.072, 8.901, 14.686, 9.912), `1997` = c(14.134, 10.548, 15.238, 10.892), `1998` = c(9.376, 5.64, 8.731, 8.19), `1999` = c(7.578, 6.232, 9.421, 8.23), `2000` = c(7.609, 5.903, 9.779, 8.478), `2001` = c(9.938, 7.198, 9.969, 7.999), `2002` = c(12.192, 8.273, 13.722, 7.095), `2003` = c(12.713, 7.953, 15.124, 9.225), `2004` = c(19.394, 11.631, 17.053,    13.506), `2005` = c(15.629, 5.779, 11.118, 10.73), `2006` = c(13.704, 
6.15, 16.641, 15.731), `2007` = c(10.824, 5.098, 12.046, 12.076)), .Names = c("1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007"), row.names = c("AC201A", "AC202A", "AC203B", "AC204A"), class = "data.frame")

我正在尝试运行for循环,导致我的data.frame中每行的移动平均值,但我不断收到警告:“在mean.default(tempy)中:参数不是数字或逻辑:返回NA“

我检查了我的列类和单个单元格,它们都是数字的,所以我不确定问题出在哪里。以下是我正在尝试运行的代码:

nrws <- dim(dafr.t)[1]    
nwind <- dim(dafr.t)[2] -5    
tmat <- as.data.frame(matrix(NA,nrow=nrws,ncol=nwind))

for ( w in 0:(nwind-1)) colnames(tmat)[1+w]<-paste(colnames(dafr.t)[4+w])    
for (tree in 1:nrws) rownames(tmat)[tree]<-rownames(dafr.t)[tree]

for (tree in 1:nrws){    
  for ( w in 0:(nwind-1)) {    
    tempx=dafr.t[tree,w+(1:3)]    
    if (sum(is.na(tempx)) > 1) next    
    tempy=dafr.t[tree,w+(4:6)]    
    if (sum(is.na(tempy)) > 1) next     
    # Calculate and capture difference    
    tmat[tree,w+1]=(mean(tempx)-mean(tempy))     
  } # close inner for loop     
} # close outer for loop

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:3)

使用mean(as.numeric(tempx))代替mean(tempx)。你也可以用

rownames(tmat)<-rownames(dafr.t)

而不是

for (tree in 1:nrws) rownames(tmat)[tree]<-rownames(dafr.t)[tree]

答案 1 :(得分:3)

您正在尝试计算data.frame的平均值。这不计算。

angular-slidezilla.js

您可以尝试取消列出data.frame

// app.js
var app = angular.module("app", ['ui.bootstrap', ..., 'angular-slidezilla']);