install.packages("dplyr")
library(dplyr)
install.packages("tibble")
library(tibble)
install.packages("stringr")
library(stringr)
score = tibble(ID=c("1222-1","2001-0","3321-1","4898-0","2782-0","1002-8","4211-0","1023-1","3325-1"),
gender=c("female","male","male","male","female","female","male","female","male") ,
chinese_mid_score=round(runif(9,80,90),digits = 0),
chinese_final_score=round(runif(9,80,90),digits = 0),
english_score=c(round(runif(8,80,90),digits = 0),NA),
match_score=round(runif(9,80,90),digits = 0),
musci_score=round(runif(9,80,90),digits = 0)
)
view(score)
rowSums
注意 S 是大写的
计算每个学生的总分
score_sum = score |>
mutate(total_score = rowSums(select(score, contains("_score")), na.rm = TRUE))
view(score_sum)
rowSums
,select
以及 contains
结合,可以灵活处理较复杂数据
contain
这种情况下不好用了,用across
score_across = score |>
mutate(total_score = rowSums(across(where(is.numeric)),na.rm=TRUE))
view(score_across)
score_change = score |>
mutate(across(.cols=where(is.numeric), .fns = ~.x/0.95, .names = "curve_{col}"))
view(score_change)
注意across
函数里命名规则,前边都需要加 dot .
其中.fns
functions函数后边有个~
,表示自定义的 function,
.names
命名时记得加""
,{col}表示每列的名字
score_pass = score |>
mutate(across(.cols=where(is.numeric), .fns = ~if_else(.x>80,"pass","fail"), .names = "pass_{col}"))
view(score_pass)
score_match = score |>
mutate(across(.cols = match_score,
.fns = ~ .x/0.95 ,
.names = "curve_{col}"
)
) |>
mutate(pass_match_score = if_else(curve_match_score>=85,"pass","fail")) |>
select(contains("match"))
view(score_match)
以上代码看着些许累赘,我们只考虑原来的成绩决定 pass or fail 就会简单许多
score_match = score |>
mutate(across(.cols = match_score,
.fns = c(curve = ~ .x/0.95 , pass = ~if_else(.>=85,"pass","fail")),
.names = "{fn}_{col}"
)
) |>
select(contains("match"))
view(score_match)
其中,.fns = c(curve = , pass = )表示两个function的名字
.names=“{fn}
_{col}”,{fn}
表示.fns
里新加的两个名字
score_summary = score |>
summarise(across(.cols = where(is.numeric),
.fns = c(
mean = ~mean(.x , na.rm = TRUE),
var = ~var(.x , na.rm = TRUE),
q5 = ~quantile(.x , 0.05, na.rm = TRUE),
q80 = ~quantile(.x , 0.8, na.rm = TRUE)
),
.names = "{fn}_{col}"))
view(score_summary)