-3

Possible Duplicate:
Compute the minimum of a pair of vectors

I have two vectors of the same length:

a <- rnorm(40)
b <- rnorm(40)

Now, I want to create a third vector c which has a each point the minor value of a and b. This could be a solution:

for (i in 1:40)
{c[i] <- min(a[i],b[i])}

However, I guess there is an easier way to do this.

Community
  • 1
  • 1
Fabian Stolz
  • 1,935
  • 7
  • 27
  • 30
  • 4
    Related (and found on the first page of search results for "min vectors"): [vectorialized parallel max() and min()?](http://stackoverflow.com/q/5591593/271616), [Compute the minimum of a pair of vectors](http://stackoverflow.com/q/7770535/271616), [max and min functions that are similar to colMeans](http://stackoverflow.com/q/7824912/271616) – Joshua Ulrich Jul 03 '12 at 16:31

2 Answers2

13

This is exactly what pmin is for... which is documented in ?min.

a <- rnorm(40)
b <- rnorm(40)
minab <- pmin(a,b)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
4

Joshua's answer is without doubt the best solution for your question. However, I sometimes personally like to use simple tools and create my own piece of code or function. Here is another way of solving the problem:

apply(data.frame(v1 = rnorm(40), v2 = rnorm(40)),1,min)
Sam
  • 4,357
  • 6
  • 36
  • 60