rdataframe

Can I change a value in a data frame using apply, with a row-wise condition?


I want to change a data frame value in my 'type' column to 'H', based on a row-wise condition where any value in a row is greater than or equal to 340.

# make data frame
df <- data.frame(
  cell_1 = c(50,10,10,125,110,300,75),
  cell_2 = c(0,75,10,70,35,70,85),
  cell_3 = c(340,230,10,10,110,10,80),
  cell_4 = c(10,75,70,70,35,10,85),
  cell_5 = c(0,10,300,125,110,10,75),
  type = c('A','A','J','U','S','L','F'),
  uniq_Id = c(1,2,3,4,5,6,7)
)

# change 'type' to 'H' if any of the cell values in each row are greater than or equal to 340
apply(df[,1:5], 1, function(i) {
  if (any(i >= 340)) {
    df$type = 'H'
  }
})

Output to the console suggests it's working. However, there's no change in the data frame after the apply function. I want 'type' in row 1 to be 'H'.

  cell_1 cell_2 cell_3 cell_4 cell_5 type uniq_Id
1     50      0    340     10      0    A       1
2     10     75    230     75     10    A       2
3     10     10     10     70    300    J       3
4    125     70     10     70    125    U       4
5    110     35    110     35    110    S       5
6    300     70     10     10     10    L       6
7     75     85     80     85     75    F       7

Solution

  • Try any of these. They are non-destructive, i.e. they preserve the input df.

    transform(df, type = replace(type, apply(df[1:5] >= 340, 1, any), "H"))
    
    transform(df, type = replace(type, apply(df[1:5], 1, max) >= 340, "H"))
    
    transform(df, type = replace(type, do.call("pmax", df[1:5]) >= 340, "H"))
    
    transform(df, type = replace(type, Reduce(pmax, df[1:5]) >= 340, "H"))
    
    library(dplyr)
    df %>%
      mutate(type = replace(type, any(pick(starts_with("cell")) >= 340), "H"), .by = uniq_Id)