3

First, I created a data frame like below:

age=18:29
height=c(76.1,77,78.1,78.2,78.8,79.7,79.9,81.1,81.2,81.8,82.8,83.5)
height1=c(71.1,75,77.1,73.2,77.8,73.7,78.9,87.1,86.2,85.8,82.8,83.5)
village=data.frame(age=age,height=height,height1=height1)

Now, I want to create a fourth column in the data frame that takes the height of the shorter person per each row, e.g. row 1 76.1 vs 71.1 should return 71.1 and so on.

I tried doing this with this code:

village=transform(village, shorter=min(height,height1))

And I got an odd result. It gives me the absolute smallest value in BOTH columns:

It gives me the absolute smallest height in BOTH columns

How can I modify this function to give me the lower value on a row-by-row basis?

IRTFM
  • 258,963
  • 21
  • 364
  • 487
AME
  • 5,234
  • 23
  • 71
  • 81

1 Answers1

15

The min function looks at only one entire vector. What you wanted was pmin which is a pairwise version of min:

> village$ageminht <- with(village, pmin(height, height1) )
> village$ageminht
 [1] 71.1 75.0 77.1 73.2 77.8 73.7 78.9 81.1 81.2 81.8 82.8 83.5

There is, of course, a pmax counterpart to return a vector of pair-maxes.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Thank you. What's the difference between the 'with' function and the 'transform' function, i.e. when would you use one versus the other? – AME Nov 12 '11 at 18:46
  • 2
    The `within` function is more like `transform` than is `with`. `with` provides an environment from which results can be returned but unless it is coupled with `<-` (assignment), it will have no permanent effect. – IRTFM Nov 12 '11 at 19:17
  • I've not yet seen much value to `within` over `with`. `within` doesn't make an actual change in an object, it only returns a value that is as large as the whole dataframe, so you still need to make an assignment with `<-` – IRTFM Jan 26 '13 at 02:51