I wanted to perform a mathematical function on each unique item in a data frame dynamically.
Normally to perform a mathematical function, we use mutate
statement and create a column and perform the mathematical function manually by writing mutate statement after mutate statement.
Which is feasible on a few columns. But what if I have 100 columns and I have to perform 2-5 mathematical function, For example: one would be 20% increase on the initial number, The other one would be to divide the initial number by 2 on each column and keep the original column as is.
Is this possible in R other than writing mutate statement for each specific item?
The data frame I am working with is:
structure(list(`Row Labels` = c("2023-03-01", "2023-04-01", "2023-05-01",
"2023-06-01", "2023-07-01", "2023-08-01", "2023-09-01", "2023-10-01"
), X6 = c(14, 16, 14, 11, 9, 9, 11, 11), X7 = c(50, 50, 50, 50,
50, 50, 50, 50), X8 = c(75, 75, 75, 75, 75, 75, 75, 75), X9 = c(100,
100, 100, 100, 100, 100, 100, 100), X11 = c(25, 25, 50, 75, 125,
200, 325, 525), X12 = c(50, 50, 100, 150, 250, 400, 650, 1050
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-8L))
For individual cases this code would suffice:
library(readxl)
library(dplyr)
Book1 <- read_excel("C:/X/X/X- X/X/Book1.xlsx",sheet = "Sheet6")
dput(Book1)
Book1 <- Book1 %>%
mutate(`X6 20%` = X6*1.20) %>%
mutate(`X6 by 2`= X6/2)
I was thinking of running this through a loop but then selection of columns to multiple becomes a problem as we have to specify the column name in mutate statement, which I believe would not be possible here right.
Can anyone let me know if this can be achieved in a simple approach?
The expected output is given below: