我有一个df,就像左边的那个,我想给每个主题加一个小计行(右边表格用黄色高亮显示),目前我的代码能够达到我的目标,但是用了一个很傻的方法,我必须一个一个的做总结,🤣有没有更聪明的方法?
# Data:
df<-structure(list(SUBJECT = c("ELA", "ELA", "ELA", "ELA", "ELA",
"Math", "Math", "Math", "Math", "Math", "Sci", "Sci", "Sci",
"Sci", "Sci"), Level = c("Grade 1", "Grade 2", "Grade 3", "Grade 4",
"Grade 5", "Grade 1", "Grade 2", "Grade 3", "Grade 4", "Grade 5",
"Grade 1", "Grade 2", "Grade 3", "Grade 4", "Grade 5"), Total = c(2,
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0), Class1 = c(0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), Class2 = c(0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Class3 = c(2, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0), Class4 = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0), Class5 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0)), row.names = c(NA, -15L), class = c("tbl_df", "tbl",
"data.frame"))
ClassLev<-c("Class1","Class2", "Class3", "Class4", "Class5")))
## Output
df2<-df %>%
group_by(SUBJECT) %>%
do(add_row(.data = .,
SUBJECT = .$SUBJECT,
Level = "All Grades",
`Class1` = sum(.$`Class1`),
`Class2` = sum(.$`Class2`),
`Class3` = sum(.$`Class3`),
`Class4` = sum(.$`Class4`),
`Class5` = sum(.$`Class5`),
Total = sum(.$`Total`),
.before = 1))%>%
distinct()
4条答案
按热度按时间ou6hu8tu1#
下面是使用
bind_rows
执行此操作的一种方法:yfjy0ee72#
我们可以使用
adorn_totals
在
devel
版本中,我们还可以将reframe
与pick
一起使用afdcj2ne3#
使用
rows_append
的另一种方法是添加汇总行:创建于2023年1月27日,使用reprex v2.0.2
zvokhttg4#
使用
Map
、rbind
和split
的基R方法由于这是一个基于行的方法,数字被转换成字符。