Search code examples
rdataframereplaceconditional-statementsmultiplication

Multiply and replace values in data frame according to condition in R


I'm new to R and I've been trying to multiply and replace certain values in my data frame with no success. Basically, what I want to do is that when a value from my df (any column) is 0 < x < 1, multiplicate it by 10 and then replace that value with the result of this equation.

A glimpse to my df just in case...

    'data.frame':   404 obs. of  15 variables:
    $ D3: num  16.1 17.1 16.1 16.1 17.2 ...
    $ TH   : num  9.9 8.6 9.7 7.7 7.6 7.6 8.7 9.8 9.8 7.7 ...
    $ D2 : num  33.3 29.3 30.3 29.3 33.3 ...
    $ D1 : num  15.1 14.1 21.1 16.1 19.1 ...
    $ P : num  20.7 14.1 19.2 18.2 12.1 ...
    $ D5 : num  9.9 11.1 11.9 11.1 11.1 ...
    $ D13: num  13.1 14.1 13.1 13.8 12.9 ...
    $ D7 : num  11.8 11.1 12.1 14.1 12.1 ...
    $ D16: num  12.9 12.1 12.9 11.1 12.9 12

For example, if a value from my data frame is 0.15 I want it to be 15.


Solution

  • An option would be to create a logical matrix based on the expression. Extract the values from the dataset, multiply by 10 and update the results

    i1 <- df1 >0 & df1 < 1
    df1[i1] <- df1[i1] * 10
    

    Or with replace if we don't want to replace the initial object

    df2 <- replace(df1, i1, df1[i1] * 10)
    

    A tidyverse option with some additional checks for type of the column would be

     library(dplyr)
     df1 %>%
        mutate_if(is.numeric, ~ case_when(between(., 0, 1) ~ . * 10, TRUE ~ .))