tintin_et_milou wrote: > > Thanks for your help, but there is some more problem. The two vectors have > not the same length so there is a problem with cbind. I give you an > example. My first vector is > > >g[g[,1]>2035 & g[,1]<2050,] > > M.Z Intensity > 2035.836 652.9494 > 2035.939 664.5841 > 2036.043 696.0554 > 2036.146 719.8969 > 2036.250 750.7660 > 2036.767 816.5243 > 2036.870 806.8539 > 2036.974 774.2397 > 2037.491 777.2780 > 2039.147 589.9075 > 2042.978 807.7167 > 2043.082 820.9365 > 2043.289 849.4942 > 2043.393 883.8975 > 2043.495 900.9681 > 2043.600 922.3238 > 2043.704 956.5985 > 2043.911 978.9377 > 2044.015 969.1999 > > and the second one is: >> f[1:9,] > M.Z Intensity Echantillon Position > 1802.809 1064.1210 1 A1 > 1865.615 8799.4880 1 A1 > 1896.426 1667.5908 1 A1 > 2001.064 515.6214 1 A1 > 2012.016 837.5599 1 A1 > 2021.589 4373.6364 1 A1 > 2028.425 832.6896 1 A1 > 2036.663 0.0000 1 A1 > 2043.497 0.0000 1 A1 > > > The two vectors have not the same number of observations and in fact i > would like to replace all the intensity of zero of the second vector by > the value of the intensity of the nearest m/Z of the first vector. > In this case, the value 816.5243 for the m/Z 2036.663 of the second vector > and 900.9681 for the intensity corresponding at m/Z=2043.497. > > Your method give me the intensity of the farest m/Z. > > Thanks you again. > Loïc > > > Ben Bolker wrote: >> >> >> >> ## construct sample data >> m1 = >> matrix(c(1000.235,1000.356, >> 125,126.5),ncol=2, >> dimnames=list(NULL,c("mZ","I"))) >> >> y = c(995.547,1000.320) >> >> ## compute distances, set diagonal to infinity >> d = as.matrix(dist(cbind(m1[,1],y))) >> diag(d) <- Inf >> >> ## find minimum distances, extract values >> cbind(y,m1[apply(d,2,which.min),2]) >> >> Ben Bolker >> >> > >
oops -- I think you should get the distance matrix via some form of distfun <- function(x1,x2) { (x1-x2)^2 } outer(m1[,1],y,distfun) my first answer was simply wrong. (I don't have time to test this -- play around to make sure I put the vectors in the right order.) cheers Ben -- View this message in context: http://www.nabble.com/comparison-of-two-vectors-tf4936213.html#a14140387 Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.