I have a bit of code that I used in an excel spreadsheet that used min
and max
that I'm trying to transfer over to R.
I have two columns, "mini"
and "maxi"
which represent a range of possible values. The third column I'm trying to populate is the proportion of that range that falls between 5 and 19. Looking at the first row in the example, if "mini"
was 10 and "maxi"
was 15, the value of the 5-19 column should be 1, since the range falls completely in that span. In row 9, the "mini"
is 1 and the "maxi"
is 3, meaning it falls completely outside of the 5-19 range, and should therefore be 0. Row 3 however, straddles this range, and only 25% falls in the range of 5-19, so the output value should be 0.25.
Edit I have updated R and although several solutions worked before, I am now getting the error:
Error in mutate_impl(.data, dots, caller_env()) :
attempt to bind a variable to R_UnboundValue
Here's an example of how the DF looks:
ID mini maxi
1 10 15
2 17 20
3 2 5
4 40 59
5 40 59
6 21 39
7 21 39
8 17 20
9 1 3
10 4 6
The code that I used previously was something like this:
=MAX((MIN(maxi,19)-MAX(mini,5)+1),0)/(maxi-mini+1)
I was initially trying to use something like
percentoutput <- mutate(DF, output = MAX((MIN(maxi,19) - MAX(mini,5) + 1),0)/(maxi-mini + 1))
This resulted in the ouput
column being full of NAs.
I wasn't sure if this is a situation where I'd need to run an apply
function, but I'm not sure how to go about setting it up. Any guidance is appreciated!
Here is an example DF:
structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), min = c(10,
17, 2, 40, 40, 21, 21, 17, 1, 4), max = c(15, 20, 5, 59, 59,
39, 39, 20, 3, 6)), class = c("spec_tbl_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -10L), spec = structure(list(
cols = list(ID = structure(list(), class = c("collector_double",
"collector")), mini = structure(list(), class = c("collector_double",
"collector")), maxi = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))