Calculations based on if the observation is found in the sample.

Hey!

Im running several loops for my project. Im trying to make a "if" statement to do some calculations based on a sample. The dataset consists of :

ID Height Diameter Rank

(Where rank is based on diameter. Meaning rank 1 is the largest and rank 2 is the second largest etc.)

Im then taking a sample from this dataset.
What I would like to do is:

if (rows with rank 1 or 2 is found in the sample)
#Do some calculations based on that single observation
OR
if(rows with rank 1 and 2 is found in the sample)
#Do some calculations based on the two observations.
else (if neither of the "if" statements are true)
#Do some calculations

Hopefully I was able to explain to problem Im having.
Thanks for any help in advance!

I hope this will sufficiently illustrate the logic of doing what you want in code. Notice that the first if test is the most restrictive, both 1 and 2 are in the sample. I did not really do any calculation but I treated the rows differently depending on there Rank. For a calculation you could use the filter() function to grab the row(s) with the desired Rank.

library(dplyr)
DF <- data.frame(Diameter = c(6,3,8,1,9,2),
                 Rank = c(3,4,2,6,1,5))
n <- 6
set.seed(124) #for a reproducible example
Rows <- vector("list", length = n)
for (i in 1:n) {
  SMPL <- sample_n(DF, 2)
  if (1 %in% SMPL$Rank & 2 %in% SMPL$Rank) {
    SMPL <- SMPL |> mutate(Picked = "Both")
  } else if (1 %in% SMPL$Rank | 2 %in% SMPL$Rank) {
    SMPL <- SMPL |> mutate(Picked = ifelse(Rank %in% 1:2, "This one", "Nope"))
  } else {
    SMPL <- SMPL |> mutate(Picked = "Nope")
  }
  Rows[[i]] <- SMPL
}
Rows
#> [[1]]
#>   Diameter Rank Picked
#> 1        6    3   Nope
#> 2        3    4   Nope
#> 
#> [[2]]
#>   Diameter Rank Picked
#> 1        8    2   Both
#> 2        9    1   Both
#> 
#> [[3]]
#>   Diameter Rank   Picked
#> 1        2    5     Nope
#> 2        9    1 This one
#> 
#> [[4]]
#>   Diameter Rank Picked
#> 1        3    4   Nope
#> 2        6    3   Nope
#> 
#> [[5]]
#>   Diameter Rank   Picked
#> 1        8    2 This one
#> 2        1    6     Nope
#> 
#> [[6]]
#>   Diameter Rank Picked
#> 1        2    5   Nope
#> 2        1    6   Nope

Created on 2022-03-23 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.