'How to make a For Loop using mutate() function
I am trying to index multiple columns of data and do not want to have multiple lines of code running.
Example:
df1 <- data.frame(
A= c(245, 1124, 1256),
B= c(548, 1145, 1248),
C = c(234, 1348, 1594),
D = c(231, 1124, 1354),
E = c(354, 1784, 1942)
)
library(tidyverse)
list <- c(A, B, C, D, E)
df2 <- df1 %>%
mutate(A = A/A[1]-1) %>%
mutate(B = B/B[1]-1) %>%
mutate(C = C/C[1]-1) %>%
... %>%
...
Unlike the example above, I have over 10 columns and over 100 rows of data, and I need to index to the 11th row and want to try using a 'for loop' to help me do this. I am very new to for loops so I am trying to learn the best way to get this done.
This is what I've tried:
for (list in df1) {
mutate(df1, list = list/list[1]-1)
}
I have also seen other threads recommending to use mutate_(), but I am not sure what the difference is.
Any help will be appreciated - my first question on Stack Overflow!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
