Search code examples
rdataframedplyrdivision

How to divide only a certain factor in a column in R data frame?


This is the sample dataset:

library(data.table)
df = data.table(x = c(1000,2000,10,2), y = c('A','A','B','B'))

I only want to divide df$y == "A" by 1000. The final dataset should appear as:

df = data.table(x = c(1,2,10,2), y = c('A','A','B','B'))

Solution

  • You need to create a conditional statement.

    In base R:

    df$x <- ifelse(df$y == "A", df$x/1000, df$x)
    

    In dplyr:

    library(dplyr)
    df <- df |>
        mutate(x = if_else(y == "A", x/1000, x))