本文介绍了按组求和变量并附加结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dataset HAVE
是Recess字符的电话数据的tibble edgelist:
Dataset HAVE
is a tibble edgelist of phone call data from the characters of Recess:
Student Friend nCalls
TJ Spinelli 3
TJ Gretchen 7
TJ Gus 6
TJ Vince 8
TJ King Bob 1
TJ Mikey 2
Spinelli TJ 3
Spinelli Vince 2
Randall Ms. Finster 17
数据集 NEED
包括来自 HAVE
的所有原始列,但包括一个新变量 nCallsPerStudent
,这正是它听起来的样子:
Dataset NEED
includes all original columns from HAVE
but includes a new variable, nCallsPerStudent
, that is exactly what it sounds like:
Student Friend nCalls nCallsPerStudent
TJ Spinelli 3 27
TJ Gretchen 7 27
TJ Gus 6 27
TJ Vince 8 27
TJ King Bob 1 27
TJ Mikey 2 27
Spinelli TJ 3 5
Spinelli Vince 2 5
Randall Ms. Finster 17 17
我如何从 HAVE
到 NEED
?
推荐答案
我们可以通过 'student' 和 mutate
分组来创建新的列
We can group by 'student' and mutate
to create the new column
library(dplyr)
df %>%
group_by(Student) %>%
mutate(nCallsPerStudent = sum(nCalls))
或者使用 base R
df$nCallsPerStudent <- with(df, ave(nCalls, Student, FUN = sum))
这篇关于按组求和变量并附加结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!