Search code examples
rdataframemultiplication

How can I multiply all values of a column except one in r?


I have a data frame

Note <- c("Revenue","Profit", "EPS", "Receipts", "Cash")
HY2020 <- c(1:5)
HY2019 <- c(6:10)

df <- data.frame(Note, HY2020, HY2019)

Is there a way to multiply the columns HY2020 and HY2019 by 1000 but leave the 'EPS' row unchanged?


Solution

  • Create a logical vector based on the 'Note' column. Use that to subset the rows, select the columns except the first column, multiply by 1000, and update by assignment (<-) back to the original same subset data

    i1 <- df$Note != "EPS"
    df[i1, -1] <- df[i1, -1] * 1000
    

    Or we use dplyr

    library(dplyr)
    df <- df %>%
         mutate(across(starts_with("HY"),
               ~ case_when(Note != "EPS" ~ . * 1000, TRUE ~ as.numeric(.))))
    

    -output

    df
     Note HY2020 HY2019
    1  Revenue   1000   6000
    2   Profit   2000   7000
    3      EPS      3      8
    4 Receipts   4000   9000
    5     Cash   5000  10000
    

    Or in data.table

    library(data.table)
    setDT(df)[Note != "EPS", (names(df)[-1]) := lapply(.SD, `*`, 1000)]