我有一個簡單的 df 如下,我想為它創建一個摘要符號。構建它的最有效方法是什么?有人可以指導我嗎?

我想構建的摘要是:
There are 2 students in ELA: G8-01, G9-08; There are 2 students in MATH: G8-09, G9-06; There is 1 student in ART: G9-04.
structure(list(ID = c("G8-01", "G8-09", "G9-08", "G9-04", "G9-05",
"G9-06", "G9-07"), ELA = c("G8-01", NA, "G9-08", NA, NA, NA,
NA), MATH = c(NA, "G8-09", NA, NA, NA, "G9-06", NA), PE = c(NA,
NA, NA, NA, NA, NA, NA), ART = c(NA, NA, NA, "G9-04", NA, NA,
NA)), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"))
uj5u.com熱心網友回復:
用于格式化字串的tidyverse解決方案:stringr::str_glue_data()
library(tidyverse)
df %>%
pivot_longer(-1, values_drop_na = TRUE) %>%
group_by(name) %>%
summarise(n = n(), id = toString(value)) %>%
str_glue_data("There {ifelse(n>1, 'are', 'is')} {n} student{ifelse(n>1, 's', '')} in {name}: {id};")
回傳
# There is 1 student in ART: G9-04;
# There are 2 students in ELA: G8-01, G9-08;
# There are 2 students in MATH: G8-09, G9-06;
uj5u.com熱心網友回復:
您通常會使用cat. 您可能希望將列及其名稱映射在一起,為了整潔,將其放在一個小函式中:
report <- function(data) {
Map(function(x, nm) {
cat('There are ', sum(!is.na(x)), " students in ", nm, ": ",
paste(x[!is.na(x)], collapse = ', '), '\n', sep = '')
}, x = data[-1], nm = names(data)[-1])
invisible(NULL)
}
這導致:
report(df)
#> There are 2 students in ELA: G8-01, G9-08
#> There are 2 students in MATH: G8-09, G9-06
#> There are 0 students in PE:
#> There are 1 students in ART: G9-04
uj5u.com熱心網友回復:
您可以pluralize()從包中使用cli。
library(cli)
library(dplyr)
library(purrr)
df %>%
select(-ID) %>%
map(discard, is.na) %>%
compact() %>%
iwalk(~ cat(pluralize("There {qty(length(.x))}{?is/are} {length(.x)} student{?s} in {qty(.y)}{.y}: {qty(.x)}{.x}"), sep = "\n"))
這給出了以下內容:
There are 2 students in ELA: G8-01 and G9-08
There are 2 students in MATH: G8-09 and G9-06
There is 1 student in ART: G9-04
如果您想在其他地方使用它,您可以調整它以回傳文本。我cat()在這個例子中只是將它列印到控制臺。
例如保存文本:
txt <- df %>%
select(-ID) %>%
map(discard, is.na) %>%
compact() %>%
imap_chr(~ pluralize("There {qty(length(.x))}{?is/are} {length(.x)} student{?s} in {qty(.y)}{.y}: {qty(.x)}{.x}"))
unname(txt)
# [1] "There are 2 students in ELA: G8-01 and G9-08"
# [2] "There are 2 students in MATH: G8-09 and G9-06"
# [3] "There is 1 student in ART: G9-04"
uj5u.com熱心網友回復:
如果您想要每個主題的報告,前面的答案已經很好了。如果您只想按照您所說的自動獲取該行,您可以使用:
首先,創建一個包含所有科目、學生人數和代碼的摘要:
example = example %>%
pivot_longer(cols=c(-ID),names_to='Subject',values_to='Code') %>%
filter(! is.na(Code)) %>%
group_by(Subject) %>%
summarise(n_students = n(),
Codes = paste0(Code, collapse=', '))
把所有東西放在一起:
lapply(example,
function(i) paste0(paste("There are",example$n_students,"students in",example$Subject,":",example$Codes),
collapse='; '))[[1]]
輸出:
[1] "There are 1 students in ART : G9-04; There are 2 students in ELA : G8-01, G9-08; There are 2 students in MATH : G8-09, G9-06"
也許lapply不是最優雅的方式,但是,它有效。此外,您可以應用as.factor到主題并創建級別以根據需要對句子進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480394.html
