gpt4 book ai didi

r - 具有频率和百分比的双向列联表

转载 作者:行者123 更新时间:2023-12-05 02:12:25 27 4
gpt4 key购买 nike

我得到了以下双向列联表,其中包含单元格百分比和频率(在括号中)。

gender       blue blue-gray       brown      dark      hazel    yellow
female 33.33% (3) 0.00% (0) 55.56% (5) 0.00% (0) 11.11% (1) 0.00% (0)
male 34.62% (9) 3.85% (1) 46.15% (12) 3.85% (1) 3.85% (1) 7.69% (2)

我用的R代码是

library(dplyr)

library(janitor)

starwars %>%
filter(species == "Human") %>%
tabyl(gender, eye_color) %>%
adorn_percentages("row") %>%
adorn_pct_formatting(digits = 2) %>%
adorn_ns()

但是,我想获得相同类型的表格,其中包含单元格频率和百分比(在括号中)。请提供任何帮助。

最佳答案

我们可以将 adorn_ns 中的 position 参数从 rear(默认)更改为 front

library(tidyverse)
starwars %>%
filter(species == "Human") %>%
tabyl(gender, eye_color) %>%
adorn_percentages("row") %>%
adorn_pct_formatting(digits = 2) %>%
adorn_ns(position = "front")
# gender blue blue-gray brown dark hazel yellow
# female 3 (33.33%) 0 (0.00%) 5 (55.56%) 0 (0.00%) 1 (11.11%) 0 (0.00%)
# male 9 (34.62%) 1 (3.85%) 12 (46.15%) 1 (3.85%) 1 (3.85%) 2 (7.69%)

或者,如果对象已经创建,则另一种选择是使用 mutate_at 进行后处理,通过捕获两个 block 中的字符来更改除第一列之外的所有列的格式,通过反转为百分比添加 () 时的反向引用

library(tidyverse)
starwars %>%
filter(species == "Human") %>%
tabyl(gender, eye_color) %>%
adorn_percentages("row") %>%
adorn_pct_formatting(digits = 2) %>%
adorn_ns() %>%
mutate_at(-1, list(~ str_replace(., "^([0-9.%]+)\\s+\\((\\d+)\\)", "\\2 (\\1)")))
# gender blue blue-gray brown dark hazel yellow
#1 female 3 (33.33%) 0 (0.00%) 5 (55.56%) 0 (0.00%) 1 (11.11%) 0 (0.00%)
#2 male 9 (34.62%) 1 (3.85%) 12 (46.15%) 1 (3.85%) 1 (3.85%) 2 (7.69%)

关于r - 具有频率和百分比的双向列联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56091794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com