Calculation of relative standard deviation with a custom function in R
I find these sorts of operations much easier to do if the input data is in a long instead of a wide format, this has the additional advantage of being faster on larger datasets. I first transform the dataset such that each row is a sample for a specific element and the columns hold the concentration and standard deviation for that combination. I then use the same logic with dplyr::mutate() to create the new rsd column.
data %&gt;%
  gather(type, value, -Sample) %&gt;%
  separate(type, c(&quot;element&quot;, &quot;type&quot;), sep=&quot;_&quot;) %&gt;%
  spread(type, value) %&gt;%
  mutate(
    rsd = ifelse(
      is.na(conc) | is.na(std) | conc == 0,
      NA,
      ifelse(
        std &gt;= conc,
        100,
        abs(100 * std / conc)
      )
    )
  )

# A tibble: 50 x 5
   Sample element    conc     std    rsd
   &lt;chr&gt;  &lt;chr&gt;     &lt;dbl&gt;   &lt;dbl&gt;  &lt;dbl&gt;
 1 A      Cu      104.    0.784   0.753 
 2 A      Fe        0.729 0.00637 0.874 
 3 A      K       284.    1.54    0.544 
 4 A      Mg       21.3   0.100   0.469 
 5 A      Mn      441.    4.59    1.04  
 6 B      Cu       32.4   0.774   2.39  
 7 B      Fe        0.783 0.0148  1.89  
 8 B      K       452.    0.474   0.105 
 9 B      Mg       43.2   0.00714 0.0165
10 B      Mn      727.    0.232   0.0319
# … with 40 more rows