我有一個這樣的資料框:
tibble(
School = c(1, 1, 2, 3, 3, 4),
City = c("A","A", "B", "C", "C", "B"),
Grade = c("7th", "7th", "7th", "6th", "8th", "8th"),
Number_Students = c(20, 23, 25, 21, 28, 34),
Type_school = c("public", "public", "private", "public", "public", "private")
)
| ID | 學校 | 城市 | 年級 | Number_Students | 型別_學校 |
|---|---|---|---|---|---|
| 1 | 1 | 一個 | 7日 | 20 | 上市 |
| 2 | 1 | 一個 | 7日 | 23 | 上市 |
| 3 | 2 | 乙 | 7日 | 25 | 私人的 |
| 4 | 3 | C | 6日 | 21 | 上市 |
| 5 | 3 | C | 8日 | 28 | 上市 |
| 6 | 4 | 乙 | 8日 | 34 | 私人的 |
分析單位是教室,但我想把它變成一個資料框,其中分析單位是學校,但有一些計算。像這樣:
tibble(
School = c(1, 2, 3, 4),
City = c("A", "B", "C", "B"),
N_6th = c(0, 0, 1, 0), # here is the number of grade 6h classrooms in each school
N_7th = c(2,1,0,0),
N_8th = c(0,0,1,1),
Students_6th = c(0, 0, 25, 0), # here is the number of students in grade 6th from each school (the sum of all 7th grade classrooms from each school)
Students_7th = c(43, 25, 0, 0),
Students_8th = c(0, 0, 28, 34),
Type_school = c("public", "private", "public", "private")
)
| 學校 | 城市 | N_6th | N_7th | N_8th | 學生_6th | 學生_7th | 學生_8th | 型別_學校 |
|---|---|---|---|---|---|---|---|---|
| 1 | 一個 | 0 | 2 | 0 | 0 | 43 | 0 | 上市 |
| 2 | 乙 | 0 | 1 | 0 | 0 | 25 | 0 | 私人的 |
| 3 | C | 1 | 0 | 1 | 25 | 0 | 28 | 上市 |
| 4 | 乙 | 0 | 0 | 1 | 0 | 0 | 34 | 私人的 |
我正在嘗試使用 pivot_wider(),但這還不足以滿足我的需求。我需要將每所學校同一年級的教室數量和每所學校同一年級的學生人數相加。
uj5u.com熱心網友回復:
進行分組并回傳計數和sum“Number_Students”,然后使用pivot_wider指定names_from為“等級”和values_from列向量
library(dplyr)
library(tidyr)
df1 %>%
group_by(School, City, Grade, Type_school) %>%
summarise(N = n(), Students = sum(Number_Students), .groups = 'drop') %>%
pivot_wider(names_from = Grade, values_from = c(N, Students), values_fill = 0)
-輸出
# A tibble: 4 × 9
School City Type_school N_7th N_6th N_8th Students_7th Students_6th Students_8th
<dbl> <chr> <chr> <int> <int> <int> <dbl> <dbl> <dbl>
1 1 A public 2 0 0 43 0 0
2 2 B private 1 0 0 25 0 0
3 3 C public 0 1 1 0 21 28
4 4 B private 0 0 1 0 0 34
uj5u.com熱心網友回復:
這是另一種方法:無法與 akrun 的完美方法相提并論,但它包含一些有趣的功能,我們可以如何獲得相同的結果:
library(tidyr)
library(dplyr)
df1 <- df %>%
pivot_wider(id_cols = c(School, City, Grade, Type_school),
names_from = "Grade",
values_from = "Number_Students",
values_fn = list(Number_Students = length),
values_fill = 0,
names_glue = "N_{Grade}")
df %>%
pivot_wider(id_cols = c(School, City, Grade, Number_Students),
names_from = Grade,
values_from = Number_Students,
values_fn = list(Number_Students = sum),
names_glue = "Students_{Grade}"
) %>%
right_join(df1, by=c("School", "City"))
School City Students_7th Students_6th Students_8th Type_school N_7th N_6th N_8th
<dbl> <chr> <dbl> <dbl> <dbl> <chr> <int> <int> <int>
1 1 A 43 NA NA public 2 0 0
2 2 B 25 NA NA private 1 0 0
3 3 C NA 21 28 public 0 1 1
4 4 B NA NA 34 private 0 0 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418386.html
標籤:
