Home > Software engineering >  In R: way to just change the max value in a row
In R: way to just change the max value in a row

Time:04-13

I am trying to change the value (minus 1 from the original value) of one specific row in a column in R and this happens to be the last row which will also always be the max value because the column is always sorted from minimum value to maximum.

Example data.frame  
    col_a 
 1  27
 2  29 
 3  35 
 4  42
 5  56
>Example Output:  
    col_a 
 1  27
 2  29 
 3  35 
 4  42
 5  55

CodePudding user response:

Here is a dplyr solution:

To apply your change to the last row, first use arrange, this will ensure that the max value is in the last row, then use an ifelse statement with last() function:

library(dplyr)

df %>% 
  arrange(col_a) %>% 
  mutate(col_a = ifelse(col_a == last(col_a), col_a-1, col_a))
  col_a
1    27
2    29
3    35
4    42
5    55

CodePudding user response:

Here is a data.table option, where we use use mult='last' to alter the last value in col_a.

library(data.table)
dt <- as.data.table(df)

dt[unique(.N), col_a := col_a - 1, mult = 'last']

Output

   col_a
1:    27
2:    29
3:    35
4:    42
5:    55

Data

df <- structure(list(col_a = c(27L, 29L, 35L, 42L, 56L)), class = "data.frame", row.names = c(NA, 
-5L))
  • Related