使用 Titanic 內置資料集,我目前計算了變數 Class 中的觀察次數。如何使用 Survive = 'Yes' 和 Survive = 'No' 的計數創建一個新列。
> as.data.frame(Titanic) %>%
mutate_if(is.character, as.factor) %>%
group_by(Class) %>%
summarise("Number of Observations" = n() )
# A tibble: 4 × 2
Class `Number of Observations`
<fct> <int>
1 1st 8
2 2nd 8
3 3rd 8
4 Crew 8
我希望得到這樣的東西
# A tibble: 4 × 2
Class `Number of Observations` Survived.Yes Survived.No
<fct> <int>
1 1st 8 4 4
2 2nd 8 4 4
3 3rd 8 4 4
4 Crew 8 4 4
我嘗試將 Survived 放在 group by 陳述句中,但它輸出到單獨的行中。
as.data.frame(Titanic) %>%
mutate_if(is.character, as.factor) %>%
group_by(Class, Survived) %>%
summarise("Number of Observations" = n() )
# A tibble: 8 × 3
# Groups: Class [4]
Class Survived `Number of Observations`
<fct> <fct> <int>
1 1st No 4
2 1st Yes 4
3 2nd No 4
4 2nd Yes 4
5 3rd No 4
6 3rd Yes 4
7 Crew No 4
8 Crew Yes 4
任何建議表示贊賞。謝謝
uj5u.com熱心網友回復:
您可以使用sum(Survived == "Yes")來獲取每個組中“是”的計數。
as.data.frame(Titanic) %>%
group_by(Class) %>%
summarise(
"Number of Observations" = n(),
across(Survived, list(Yes = ~ sum(. == "Yes"),
No = ~ sum(. == "No"))))
# # A tibble: 4 x 4
# Class `Number of Observations` Survived_Yes Survived_No
# <fct> <int> <int> <int>
# 1 1st 8 4 4
# 2 2nd 8 4 4
# 3 3rd 8 4 4
# 4 Crew 8 4 4
您還可以使用pivot_wider()from tidyr:
library(tidyr)
as.data.frame(Titanic) %>%
add_count(Class, name = "Number of Observations") %>%
pivot_wider(c(Class, last_col()),
names_from = Survived, names_prefix = "Survived_",
values_from = Survived, values_fn = length)
# # A tibble: 4 x 4
# Class `Number of Observations` Survived_No Survived_Yes
# <fct> <int> <int> <int>
# 1 1st 8 4 4
# 2 2nd 8 4 4
# 3 3rd 8 4 4
# 4 Crew 8 4 4
您甚至不需要附加其他包。
addmargins(xtabs(~ Class Survived, Titanic), 2)
# Survived
# Class No Yes Sum
# 1st 4 4 8
# 2nd 4 4 8
# 3rd 4 4 8
# Crew 4 4 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466668.html
