R 按组求和变量并将其作为新变量添加到数据帧中
现在我有一个来自游戏日(名为:games_day)的数据框,看起来像这样 我想在数据框中创建一个新的变量,将每个团队的总分相加,这样看起来就像这样 到目前为止,我已经在dplyr中使用了这段代码R 按组求和变量并将其作为新变量添加到数据帧中,r,dplyr,R,Dplyr,现在我有一个来自游戏日(名为:games_day)的数据框,看起来像这样 我想在数据框中创建一个新的变量,将每个团队的总分相加,这样看起来就像这样 到目前为止,我已经在dplyr中使用了这段代码 games\u day%>%group\u by(团队id)%>%summary(总分=sum(总分)) 但这不会将其作为新变量添加到数据帧中。如果您对此有任何帮助,我们将不胜感激请尝试以下方法: library(tidyverse) #Data df <- structure(list(te
games\u day%>%group\u by(团队id)%>%summary(总分=sum(总分))
但这不会将其作为新变量添加到数据帧中。如果您对此有任何帮助,我们将不胜感激请尝试以下方法:
library(tidyverse)
#Data
df <- structure(list(team_id = c("Red", "Blue", "Yellow", "Red", "Blue",
"Yellow"), date = c("18/01/20", "18/01/20", "19/01/20", "19/01/20",
"20/01/20", "20/01/20"), points_for = c(16L, 12L, 10L, 9L, 17L,
13L), points_against = c(12L, 16L, 9L, 10L, 13L, 17L)), class = "data.frame", row.names = c(NA,
-6L))
#Code
df %>% group_by(team_id) %>% mutate(total_points_for=sum(points_for,na.rm=T),
total_points_against=sum(points_against,na.rm=T))
# A tibble: 6 x 6
# Groups: team_id [3]
team_id date points_for points_against total_points_for total_points_against
<chr> <chr> <int> <int> <int> <int>
1 Red 18/01/20 16 12 25 22
2 Blue 18/01/20 12 16 29 29
3 Yellow 19/01/20 10 9 23 26
4 Red 19/01/20 9 10 25 22
5 Blue 20/01/20 17 13 29 29
6 Yellow 20/01/20 13 17 23 26
库(tidyverse)
#资料
df%分组依据(团队id)%>%变异(总分数=sum(分数=na.rm=T),
总分数=总和(分数=T)
#一个tibble:6x6
#组别:组别编号[3]
团队id日期分数针对总分数针对总分数针对总分数
1红色18/01/20 16 12 25 22
2蓝色18/01/20 12 16 29 29
3黄色19/01/20 10 9 23 26
4红色19/01/20 9 10 25 22
5蓝色20/01/20 17 13 29
6黄色20/01/20 13 17 23 26
使用变换的基本R选项
+ave
transform(df,
total_points_for = ave(points_for, team_id, FUN = sum),
total_points_against = ave(points_against, team_id, FUN = sum)
)
将summary()
替换为mutate()
Hi b1lly\u孩子!欢迎来到堆栈溢出!请查看以下内容并相应更新您的帖子: