Replacing specific values across multiple rows

Viewed 42

I have a data file with multiple columns and hundreds of rows similar to this demo table:

0.91304348 0.08333333 0.25000000 1.00000000 1.00000000 0.85714286 0.08333333 0.43478261 0.12500000 1.00000000 1.00000000 1.00000000 0.16666667 1.00000000 1.00000000

I would like to look through all values and replace any value that is greater than 0.5 by subtracting 0.5 from the value and replacing it with the resultant value. So for example if the value is 0.85714286, I'd replace that value with 0.35714286 (i.e 0.85714286 - 0.5). But a value that is <=0.5 should be left as is.

By this, the above demo table would look like this;

0.41304348 0.08333333 0.25000000 0.50000000 0.50000000 0.55714286 0.08333333 0.43478261 0.12500000 0.50000000 0.50000000 0.50000000 0.16666667 0.50000000 0.50000000

I am trying to execute a for loop in R but so far unsuccessful (being a beginner)

New_Table <-c()

for (i in 1:nrowTable) {
     if (i > 0.5) {
        New_Table <- (i - 0.5)
 } else {
   New_Table <- Table[i]
  }
 }  

Please advise, I appreciate any help in R (or other possible approaches for learning purpose)

Thank you!

3 Answers

We can create a logical matrix and use that index to replace the values by subtracting and assign it to those corresponding locations

i1 <- m1 > 0.5
m1[i1] <- m1[i1] - 0.5

We could use across with case_when

library(dplyr)
df %>% 
  mutate(across(where(is.numeric), 
                ~ case_when(. > 0.5 ~ .-0.5,
                            TRUE ~ .)))

Output:

     X1     X2    X3    X4    X5    X6     X7     X8 X9   
  <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>  <dbl> <lgl>
1 0.413 0.0833  0.25   0.5 0.5   0.357 0.0833  0.435 NA   
2 0.125 0.5     0.5    0.5 0.167 0.5   0.5    NA     NA 

In case you would also like to use a for loop:

for(i in 1:nrow(df)) {
  for(j in 1:ncol(df)) {
    if(df[i, j] > 0.5) {
      df[i, j] <- df[i, j] - 0.5
    }
  }
}
df

           a         b
1 0.91304348 0.4347826
2 0.08333333 0.1250000
3 0.25000000 1.0000000
4 1.00000000 1.0000000
5 1.00000000 1.0000000
6 0.85714286 0.1666667
7 0.08333333 1.0000000

data

0.08333333), b = c(0.43478261, 0.125, 1, 1, 1, 0.16666667, 1)), class = "data.frame", row.names = c(NA, 
-7L))
Related