So, I have a dataset like the below
a <- c(a,b,c,d)
b <- c(1:4)
c <- c(1:4)
d <- c(1:4)
df <- data.frame(a,b,c,d)
I want to subtract the first value from column ‘b’, ‘c’ and ‘d’ from all rows in the column. I know how to do this for one column (like below), but is there a way to loop this for all columns?
df$b <- df$b - df[1,2]
>Solution :
library(dplyr)
df %>%
mutate(across(b:d, ~ .x - first(.x)))
a b c d
1 a 0 0 0
2 b 1 1 1
3 c 2 2 2
4 d 3 3 3