How can we apply the function for every 3 columns in dataframe.
Example is as below.
I am not sure how dplyr or map or purrr could be used here to
our motto "Do not repeat yourself"
df <- data.frame(a = runif(10, 2.0, 7.5),
b = runif(10, 5.0, 9.5),
c = runif(10, 1.0, 9.5),
d = runif(10, 2.0, 9.1),
e = runif(10, 3.0, 9.2),
f = runif(10, 4.0, 9.3),
g = runif(10, 5.0, 9.4),
h = runif(10, 6.0, 9.5),
i = runif(10, 7.0, 9.6),
j = runif(10, 8.0, 9.7),
k = runif(10, 9.0, 9.8),
l = runif(10, 1.0, 9.9)
)
df[,1:3] = sweep(df[,1:3],1,rowSums(df[,1:3]),`/`)*100
df[,4:6] = sweep(df[,4:6],1,rowSums(df[,4:6]),`/`)*100
df[,7:9] = sweep(df[,7:9],1,rowSums(df[,7:9]),`/`)*100
df[,10:12] = sweep(df[,10:12],1,rowSums(df[,10:12]),`/`)*100
Can we have a single function to apply sweep function for every 3 columns instead of hardcoding with 3 extra lines as above ?
Thanks in advance