ginn
ginn

Reputation: 151

Subtract values using a condition based on several columns

I have a data frame with five variables and 108 observations. The variables are: treatment, replicate, particle size, concentration, and mass. It looks like this:

> dput (head (bq))

structure(list(Treatment = c(1, 1, 1, 1, 1, 1), Replicate = c(1, 
2, 3, 1, 2, 3), ParticleSize = c(100, 100, 100, 100, 100, 100
), Concentration = c(0, 0, 0, 25, 25, 25), Mass = c(0.238, 0.249, 
0.263, 0.239, 0.245, 0.246)), row.names = c(NA, 6L), class = "data.frame")

> head (bq)

  Treatment Replicate ParticleSize Concentration  Mass
1         1         1          100             0 0.238
2         1         2          100             0 0.249
3         1         3          100             0 0.263
4         1         1          100            25 0.239
5         1         2          100            25 0.245
6         1         3          100            25 0.246

But I wanted to group the values by Treatment, Particle Size, and Concentration to subtract Mass values where Concentration is not 0 by where it is.

Examples:

Subtract the mass value from where treatment == 1, replicate == 1, particle size == 100, concentration == 25 by where treatment == 1, replicate == 1, particle size == 100, concentration == 0

Subtract the mass value from where treatment == 1, replicate == 2, particle size == 100, concentration == 25 by where treatment == 1, replicate == 2, particle size == 100, concentration == 0

And so on

This is my code:

bq <- read.xlsx (file = "./data/xxx.xlsx", 
                 sheetIndex = 1, as.data.frame = T, header = T)                                |>
      mutate    (Treatment = as.factor (Treatment),
                 Treatment = factor (Treatment, levels = c("CHOS", "PTN", "AFC")),
                 Treatment = as.numeric (Treatment))                                           |>
      group_by  (Treatment, ParticleSize, Concentration)                                       |>
      mutate    (Mass = ifelse (Mass > 0, Mass - Mass [Concentration == 0], Mass))             |> 
      ungroup   ()

I mean, I guess the problem is ```Mass - Mass [Concentration == 0]``, but I have no idea how to get it right...

Upvotes: 0

Views: 53

Answers (0)

Related Questions