Compare dataframe columns with vectors to obtain lower and upper bounds

I have a dataframe which represents changes in some variable. I want small changes, smaller than some quantities given by a vector, to be 0 and big changes, again given by a vector, to be capped by the vector element.

I was able to achieve the fisrt part by creating a dataframe with the vector with the minimum values, comparing it to the original dataframe and setting TRUE values to be 0. This fails for the other part, since I don’t know which element of the vector to use.

Here is some sample data:

A=structure(list(V1 = c(0.108762394171208, 0.462799827801064, 0.391699776984751, 
                        0.701799504924566), V2 = c(0.226724285865203, 0.163136613089591, 
                        0.428917320212349, 0.538211710518226), V3 = c(0.929441494401544, 
                        0.0767909574788064, 0.144388129469007, 0.555204615229741)),
                        class = "data.frame", row.names = c(NA, -4L))

Amin=c(0.15,0.12,0.08)
Amax=c(0.65,0.9,0.8)

The result I want is

> A_res
         V1        V2        V3
1 0.0000000 0.2267243 0.8000000
2 0.4627998 0.1631366 0.0000000
3 0.3916998 0.4289173 0.1443881
4 0.6500000 0.5382117 0.5552046

>Solution :

A possible solution, in base R:

t(apply(A, 1, \(x) ifelse(x > Amax, Amax, ifelse(x < Amin, Amin, x))))

#>             V1        V2        V3
#> [1,] 0.1500000 0.2267243 0.8000000
#> [2,] 0.4627998 0.1631366 0.0800000
#> [3,] 0.3916998 0.4289173 0.1443881
#> [4,] 0.6500000 0.5382117 0.5552046

Leave a Reply