i have dataframe 3 values, x , y coordinates , z value of indipendent variable:
x.range <- c(1,10) y.range <- c(20,50) grid <- expand.grid(x = seq(x.range[1], x.range[2], by=0.5), y = seq(y.range[1], y.range[2], by=0.5)) grid$z <- runif(nrow(grid),10, 70)
now have dataframe x , y values:
x1 <- c(3.7,5.4,9.2) y1 <- c(41.1,30.3,22.9) df <- data.frame(x=x1,y=y1)
now want associate points of dataframe df
z value of nearest point of dataframe grid
(with shortest distance). thanks.
this isn't prettiest, works
apply(df, 1, function(x){ pythag <- sqrt((x[1] - grid$x)^2 + (x[2] - grid$y)^2) grid[which.min(pythag), "z"] })
simply returning value nearest point using pythagoras.
edit
recoding adhere coding standards:
pythag <- function(x, y, g){ which.min(((x - g$x)^2 + (y - g$y)^2)^0.5) } idx <- mapply(fun = pythag, x = df[["x"]], y = df[["y"]], moreargs = list(g = grid)) grid[idx,]
Comments
Post a Comment