[R] problem applying a conditional formula to each element of a matrix

Dale Steele dale.w.steele at gmail.com
Wed Dec 12 22:35:51 CET 2007


I'm applying a function (Cov.f) defined below to each element of a
distance matrix.  When I run the code below, I get a warning message
(below) and elements of returned matrix [2,3] and [3,2] are not zero
as I would expect. Clearly, there is an error... What am I doing
wrong? Thanks.  --Dale

Warning message:
In if (h <= phi) { :
  the condition has length > 1 and only the first element will be used

# function

Cov.f <- function(h, sigmasq, phi) {
  if (h <= phi) {Cij <- sigmasq * (1 - ( 1.5 * (h/phi)  - 0.5 *
(h/phi)^3))  } else
  if (h > phi)  {Cij <- 0}
  return(Cij)
      }

x.coord <- c(5.7, 6.7, 9.8)
y.coord <- c(42.7, 10.2, 77.4)
coords <- cbind(x.coord, y.coord)
distance.matrix <- as.matrix(dist(coords, method="euclidean"))
distance.matrix
Cov.f(distance.matrix, 3.9, 58.1)



More information about the R-help mailing list