我有下面的代码来计算一定数量的兴趣,特别是两个最右边的列之和。
library(dplyr)
library(janitor)
m = c(0, 0.8, 2.3, 4.1, 2.1)
l = c(0.3, 0.8, 0.9, 0.75, 0.25)
mytable = data.frame(l, m)
rownames(mytable) = paste("Group", 1:5)
# Initial population
n0 = c(1,1,1,1,1)
mytable = mytable %>%
mutate(lm = l * m) %>%
mutate(n = n0) %>%
mutate(offspring = lm * n) %>%
adorn_totals("row")
这提供了以下输出:
> mytable
l m lm n offspring
0.3 0.0 0.000 1 0.000
0.8 0.8 0.640 1 0.640
0.9 2.3 2.070 1 2.070
0.75 4.1 3.075 1 3.075
0.25 2.1 0.525 1 0.525
Total 9.3 6.310 5 6.310
我有以下问题:
n
和offspring
列的汇总。我阅读了adorn_totals()
函数的文档,但我不知道如何做到这一点。发布于 2021-10-27 20:51:10
一个选项是将所需列以外的列转换为character
类,然后在以后更改它。关于行名,tibble
不允许行名。我们可能需要首先用rownames_to_column
创建一个列
library(dplyr)
library(tibble)
library(janitor)
out <- mytable %>%
rownames_to_column('rn') %>%
mutate(lm = l *m, n = n0, offspring = lm * n) %>%
mutate(across(-c(n, offspring), as.character)) %>%
adorn_totals('row', fill = NA) %>%
type.convert(as.is = TRUE)
-output
> out
rn l m lm n offspring
Group 1 0.30 0.0 0.000 1 0.000
Group 2 0.80 0.8 0.640 1 0.640
Group 3 0.90 2.3 2.070 1 2.070
Group 4 0.75 4.1 3.075 1 3.075
Group 5 0.25 2.1 0.525 1 0.525
Total NA NA NA 5 6.310
> str(out)
Classes ‘tabyl’ and 'data.frame': 6 obs. of 6 variables:
$ rn : chr "Group 1" "Group 2" "Group 3" "Group 4" ...
$ l : num 0.3 0.8 0.9 0.75 0.25 NA
$ m : num 0 0.8 2.3 4.1 2.1 NA
$ lm : num 0 0.64 2.07 3.075 0.525 ...
$ n : int 1 1 1 1 1 5
$ offspring: num 0 0.64 2.07 3.075 0.525 ...
- attr(*, "core")='data.frame': 5 obs. of 6 variables:
..$ rn : chr [1:5] "Group 1" "Group 2" "Group 3" "Group 4" ...
..$ l : chr [1:5] "0.3" "0.8" "0.9" "0.75" ...
..$ m : chr [1:5] "0" "0.8" "2.3" "4.1" ...
..$ lm : chr [1:5] "0" "0.64" "2.07" "3.075" ...
..$ n : num [1:5] 1 1 1 1 1
..$ offspring: num [1:5] 0 0.64 2.07 3.075 0.525
- attr(*, "tabyl_type")= chr "two_way"
- attr(*, "totals")= chr "row"
发布于 2021-10-28 18:39:29
对于第一和第三点:您可以通过为...
参数adorn_totals()
指定列名来控制哪些列是总计的。使用...
需要为其他参数指定值,即使它们是空的,因此下面的,,,,
接受这些参数的默认值。
默认情况下跳过第一列,因为这通常是一个组ID (就像您的行名一样),但是您可以指定应该对其进行总计。
下面是如何总计列l
、n
和offspring
mytable %>%
mutate(lm = l * m) %>%
mutate(n = n0) %>%
mutate(offspring = lm * n) %>%
adorn_totals("row",,,,l, n, offspring)
返回:
l m lm n offspring
0.30 0 0 1 0.000
0.80 0.8 0.64 1 0.640
0.90 2.3 2.07 1 2.070
0.75 4.1 3.075 1 3.075
0.25 2.1 0.525 1 0.525
3.00 - - 5 6.310
连同警告:
,因为第一列被指定为总计,因此它不包含总计行
中的标签“Total”(或用户指定的名称)。
https://stackoverflow.com/questions/69745242
复制相似问题