So I have a function that I want to apply to a range of columns in my dataframe
My dataframe has 111 columns and I want to de-mean each column based on its ID number.
I have the following code for the column named esgscore
demeaned_df <- df %>%
group_by(ID) %>%
mutate(avg_esgscore = mean(esgscore)) %>%
mutate(demeaned_esgscore = esgscore - avg_esgscore)
This does exactly what I want so I am happy with it but I essentially want to apply this function to columns 3:111 in my dataframe (df) and put these into a new dataframe called demeaned_df
Any help would be greatly appreciated
Here is one idea. We can use across
to apply the function to multiple columns. In this example, I applied the demean operation to columns from disp
to carb
.
library(dplyr)
mtcars2 <- mtcars %>%
group_by(cyl) %>%
mutate(across(disp:carb, .fns = function(x) x - mean(x)))
mtcars2
# # A tibble: 32 x 11
# # Groups: cyl [3]
# mpg cyl disp hp drat wt qsec vs am gear carb
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 21 6 -23.3 -12.3 0.314 -0.497 -1.52 -0.571 0.571 0.143 0.571
# 2 21 6 -23.3 -12.3 0.314 -0.242 -0.957 -0.571 0.571 0.143 0.571
# 3 22.8 4 2.86 10.4 -0.221 0.0343 -0.527 0.0909 0.273 -0.0909 -0.545
# 4 21.4 6 74.7 -12.3 -0.506 0.0979 1.46 0.429 -0.429 -0.857 -2.43
# 5 18.7 8 6.90 -34.2 -0.0793 -0.559 0.248 0 -0.143 -0.286 -1.5
# 6 18.1 6 41.7 -17.3 -0.826 0.343 2.24 0.429 -0.429 -0.857 -2.43
# 7 14.3 8 6.90 35.8 -0.0193 -0.429 -0.932 0 -0.143 -0.286 0.5
# 8 24.4 4 41.6 -20.6 -0.381 0.904 0.863 0.0909 -0.727 -0.0909 0.455
# 9 22.8 4 35.7 12.4 -0.151 0.864 3.76 0.0909 -0.727 -0.0909 0.455
# 10 19.2 6 -15.7 0.714 0.334 0.323 0.323 0.429 -0.429 0.143 0.571
# # ... with 22 more rows
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.