In my data cleansing, I have multiple dimension columns with a name in them that need to be aggregated by multiple metric columns. The same code needs to be applied to my dimension columns. I can easily enough copy and paste the same chunk of code ten times and change the column reference, however surely there is a simpler solution.
My research is leading me to believe I am missing something obvious with the sapply() function that I can't put my finger on.
Very basic reprex:
library(tidyverse)
player_1 <- c("Smith", "Adams", "Washington")
player_2 <- c("Johnson", "Jefferson", "Fuller")
player_3 <- c("Forman", "Hyde", "Kelso")
metric_1 <- 1:3
metric_2 <- 2:4
metric_3 <- 3:5
df <- data.frame(player_1, player_2, player_3, metric_1, metric_2, metric_3)
p1 <- df %>%
group_by(player_1) %>%
summarize_at(c("metric_1", "metric_2", "metric_3"), sum)
Is there a way to only have to type this "p1" code once but have R loop through my columns player_1, player_2, and player_3?
If I can provide more detail, please let me know.
question from:
https://stackoverflow.com/questions/66056229/r-applying-the-same-code-to-multiple-columns 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…