我有一個像下面這樣的資料集,有100多行。我想按年份和學校來平均學生的分數。因此,我將為2019年的ISD 1和2020年的ISD 1提供一個分數,等等。我正在使用這段代碼來做到這一點。
df <- df %>%
group_by(Year, `School Name`) %>%
summarise(across(everything(), . f = list(mean = mean)/span>。 na. rm = TRUE))
但是我需要平均數的n個數。我想知道有多少學生得到了平均數。我如何用NAs做這件事呢?
| 年份 | 學校名稱 | 學生分數學生分數|
|---|---|---|
| 2019年 | ISD 11 | 2020 |
uj5u.com熱心網友回復:
如果我理解正確,這可能對你有幫助
#Libraries
library(tidyverse)
library(lubridate)
#Data
df<-
tibble::tribble()
~年, ~學校.姓名, ~學生. Score1, ~Student.Score2,
2019L, "ISD 1"/span>。 1L, NA, NA,
2020L, "ISD 4"/span>。 4L, 2L,
2020L, "ISD 3"/span>。 NA, 3L, 3L,
2018L, "ISD 1"/span>。 4L, NA, NA,
2019L, "ISD 4"/span>。 2L, 5L,
2020L, "ISD 4"/span>。 3L, 2L,
2019L, "ISD 3"/span>。 NA, 1L, 1L,
2018L, "ISD 1"/span>。 2L, 4L[/span
)
#How to
df %>%
group_by(Year,School.Name) %>;%
summarise()
n = n(),
across(.cols = contains(" 。 Score"),。 fns = function(x)/span>mean(x。 娜。 rm = TRUE))
)
# A tibble: 6 x 5
# 組。 年級[3]
年級 學校名稱 n 學生.分數1 學生.分數2
<int> <chr> < int> <dbl> > <dbl>
1 2018 ISD 1 2 3 4
2 2019 ISD 1 1 1 NaN
3 2019 ISD 3 1 NaN 1
4 2019 ISD 4 1 2 5
5 2020 ISD 3 1 NaN 3
6 2020 ISD 4 2 3.
uj5u.com熱心網友回復:
我猜測Student Score列代表獨立的學生,他們應該與同一學校、同一年級的其他學生結合起來看。如果是這樣的話,那么你可能應該先將你的資料重塑為長格式,就像下面這樣:
library(dplyr); library(tidyr)
df %> %
# reshape, keeping Year and School Name as keys[/span].
pivot_longer(-c(Year, /span> `School. Name`)) %>%
group_by(Year,`School.Name`) %>%
filter(! is. na(value)) %>%
summarise(mean = mean(value),>
n = n(), 。 groups = "drop") 。
結果
Year School.Name mean n
<int> <chr> <dbl> <int>
1 2018 ISD 1 4 1
2 2018 ISD1 3 2
3 2019 ISD 1 1 1
4 2019 ISD 3 1 1 ISD
5 2019 ISD 4 3.5 2
6 2020 ISD 3 3 1 ISD
7 2020 ISD 4 2.75 4
(注意,我按原樣使用了資料,但我懷疑 "ISD1 "和 "ISD1 "應該是同一種東西,在這種情況下,你可能需要先做一些資料清理。)
起始資料:
"ISD1 "和 "ISD1 "應該是同一種東西。
起始資料:(注意,非唯一命名的學生分數列被data.frame函式重命名為唯一的名稱,例如Student.Score和Student.Score.1)
df <- data.frame()
stringsAsFactors = FALSE,
年份 = c(2019L。 2020L, 2020L, 2018L。 2019L, 2020L。 2019L, 2018L),
`學校名稱` = c("ISD 1"。 "ISD 4","ISD 3",
"ISD 1","ISD 4","ISD 4"。 "ISD 3","ISD1"),
`學生分數` = c(1L。 4L, NA, 4L。 2L, 3L。 NA, 2L),
`學生分數` = c(NA。 2L, 3L。 NA, 5L, 2L。 1L, 4L)
)
uj5u.com熱心網友回復:
透視更長的時間可能是一個好方法。
df %>%
pivot_longer(cols = c(-年。 -`School Name`)) %> %
group_by(Year,`School Name`) %>%
summarise(mean = mean(value, na. rm = T))。
輸出
# A tibble: 6 x 3
# Groups: 年級[3]
年級`學校名稱`的意思
<int> < chr> <dbl>/span>
1 2018 ISD 1 3.33
2 2019 ISD 1 1
3 2019 ISD 3 1
4 2019 ISD 4 3.
5 2020 ISD 3 3
6 2020 ISD 4 2.75
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332212.html
標籤:
上一篇:在管道作業流程中對大量標準使用case_when而不使用rowwise
下一篇:R中的時間序列的Ewma回報率
