Home > Net >  How I can calculate the max for these data
How I can calculate the max for these data

Time:04-08

Here is a part of my data

dat<-read.table (text="
Flower  A1  A2  A3  TM  MN  B1  B2  B3
F1  12  9   11  12  0.56    19  1   12
F2  11  16  13  13  0.65    22  4   12
F3  10  12  14  11  0.44    29  9   12
", header=TRUE)

I want to calculate Max for column MN. For example, for value 0.44, the max is max(0.44,1-0.44)= 0.56. I struggle to get it with a data frame.

Here is the outcome of the interest:

Flower  A   TM  B   MN  Max
F1  12  12  19  0.56    0.56
F2  11  13  22  0.65    0.65
F3  10  11  29  0.44    0.56
F1  9   12  1   0.56    0.56
F2  16  13  4   0.65    0.65
F3  12  11  9   0.44    0.56
F1  11  12  12  0.56    0.56
F2  13  13  12  0.65    0.65
F3  14  11  12  0.44    0.56

CodePudding user response:

Try the code below

transform(
    reshape(
        setNames(dat, gsub("(\\d )", ".\\1", names(dat))),
        direction = "long",
        idvar = c("Flower", "TM", "MN"),
        varying = -c(1, 5, 6)
    ),
    Max = pmax(MN, 1 - MN)
)

which gives

             Flower TM   MN time  A  B  Max
F1.12.0.56.1     F1 12 0.56    1 12 19 0.56
F2.13.0.65.1     F2 13 0.65    1 11 22 0.65
F3.11.0.44.1     F3 11 0.44    1 10 29 0.56
F1.12.0.56.2     F1 12 0.56    2  9  1 0.56
F2.13.0.65.2     F2 13 0.65    2 16  4 0.65
F3.11.0.44.2     F3 11 0.44    2 12  9 0.56
F1.12.0.56.3     F1 12 0.56    3 11 12 0.56
F2.13.0.65.3     F2 13 0.65    3 13 12 0.65
F3.11.0.44.3     F3 11 0.44    3 14 12 0.56

CodePudding user response:

Using reshape and ave.

reshape(dat, varying=list(2:4, 7:9), direction='long', idvar='Flower') |>
  transform(Max=ave(MN, Flower, FUN=max))
#      Flower TM   MN time A1 B1  Max
# F1.1     F1 12 0.56    1 12 19 0.56
# F2.1     F2 13 0.65    1 11 22 0.65
# F3.1     F3 11 0.44    1 10 29 0.44
# F1.2     F1 12 0.56    2  9  1 0.56
# F2.2     F2 13 0.65    2 16  4 0.65
# F3.2     F3 11 0.44    2 12  9 0.44
# F1.3     F1 12 0.56    3 11 12 0.56
# F2.3     F2 13 0.65    3 13 12 0.65
# F3.3     F3 11 0.44    3 14 12 0.44

Note: R >= 4.1 used.

  •  Tags:  
  • r
  • Related