簡體   English   中英

R - 將相同的代碼應用於多列

[英]R - Applying the Same Code to Multiple Columns

在我的數據清理中,我有多個維度列,其中包含需要由多個指標列聚合的名稱。 相同的代碼需要應用於我的維度列。 我可以很容易地復制和粘貼相同的代碼塊十次並更改列引用,但是肯定有一個更簡單的解決方案。

我的研究讓我相信我在 sapply() function 中遺漏了一些我無法理解的明顯東西。

非常基本的代表:

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)

有沒有辦法只需要鍵入這個“p1”代碼一次,但讓 R 循環通過我的列 player_1、player_2 和 player_3?

如果我能提供更詳細的信息,請告訴我。

幾個選項:

  1. 使用map並分別迭代每個播放器。
library(tidyverse)

cols <- paste0('player_', 1:3)

map(cols, ~df %>% 
           group_by(.data[[.x]]) %>% 
            summarise(across(starts_with('metric'), sum)))

#[[1]]
# A tibble: 3 x 4
#  player_1   metric_1 metric_2 metric_3
#* <chr>         <int>    <int>    <int>
#1 Adams             2        3        4
#2 Smith             1        2        3
#3 Washington        3        4        5

#[[2]]
# A tibble: 3 x 4
#  player_2  metric_1 metric_2 metric_3
#* <chr>        <int>    <int>    <int>
#1 Fuller           3        4        5
#2 Jefferson        2        3        4
#3 Johnson          1        2        3

#[[3]]
# A tibble: 3 x 4
#  player_3 metric_1 metric_2 metric_3
#* <chr>       <int>    <int>    <int>
#1 Forman          1        2        3
#2 Hyde            2        3        4
#3 Kelso           3        4        5

  1. 獲取長格式數據。
df %>%
  pivot_longer(cols = starts_with('player')) %>%
  group_by(name, value) %>%
  summarise(across(starts_with('metric'), sum))

#  name     value      metric_1 metric_2 metric_3
#  <chr>    <chr>         <int>    <int>    <int>
#1 player_1 Adams             2        3        4
#2 player_1 Smith             1        2        3
#3 player_1 Washington        3        4        5
#4 player_2 Fuller            3        4        5
#5 player_2 Jefferson         2        3        4
#6 player_2 Johnson           1        2        3
#7 player_3 Forman            1        2        3
#8 player_3 Hyde              2        3        4
#9 player_3 Kelso             3        4        5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM