Search code examples
arraysrvectorlimit

Capping each member in an r array


I'm new to R and I have losses data:

losses=c(25,250,5,17,2,195,12,8,75,5,50,1);

How to cap each member of the list at 150? Namely how to perform min(150,x) for each member of the list?

Then I want to cap all losses at 'amount of insurance' array:

aoi=c(150,250,100,125,300,200,80,250,100,350,500,120) 

Solution

  • See ?pmin, or parallel minima calculation:

    pmin(150,losses)
    #[1]  25 150   5  17   2 150  12   8  75   5  50   1
    

    If you need to do this multiple times, it would be beneficial to collect your variables in a data.frame or list. E.g.:

    dat <- data.frame(losses,aoi)
    data.frame(Map(pmin,dat,150))
    
    #   losses aoi
    #1      25 150
    #2     150 150
    #3       5 100
    #etc...