如何在 R Markdown 中将空向量对应的站点数量显示为 0?
用向量长度统计数量,空向量会得到 0
可以。length(repeats) 在 repeats 为空时返回 0。要统计不同 SiteId 的数量,可以使用 length(unique(repeats)),也可以保留原来的 dplyr::n_distinct(repeats)。
repeats <- numeric(0)
length(repeats)
# [1] 0
dplyr::n_distinct(repeats)
# [1] 0
需要区分站点数量和站点编号列表。numeric(0) 表示向量中没有元素;as.integer(repeats) 仍然是空向量,不会自动生成一个 0。n_distinct(repeats) 返回的是数量,对空向量返回 0。
如果原来的 n_distinct(repeats) 没有在文档中显示数字,给出的代码还不足以确定原因;空向量本身不会让这个计数函数返回空结果。
在 R Markdown 中直接输出计数
保留现有的 repeats 计算代码后,可以在报告中这样写:
There were `r length(unique(repeats))` sites repeated this month.
没有重复站点时,会生成:
There were 0 sites repeated this month.
也可以继续使用原来的函数,明确指定命名空间:
There were `r dplyr::n_distinct(repeats)` sites repeated this month.
这种写法需要已安装 dplyr。行内表达式必须放在反引号之间,计算 repeats 的代码块也需要在行内表达式之前执行。
根据数量自动生成整句话
如果希望在没有重复站点时显示 0 (zero),并省略后面的站点列表,可以先在 R 代码块中生成报告文字:
# 提取两个月共有的站点,并去除重复的 SiteId
repeats <- unique(
this_month$SiteId[this_month$SiteId %in% last_month$SiteId]
)
n_repeats <- length(repeats)
report_text <- if (n_repeats == 0L) {
"There were 0 (zero) sites repeated this month."
} else {
sprintf(
"There were %d sites repeated this month. These were Sites: %s.",
n_repeats,
paste(repeats, collapse = ", ")
)
}
然后在 R Markdown 正文中引用:
`r report_text`
题目中的两个场景分别会生成:
There were 2 sites repeated this month. These were Sites: 102, 104.
以及:
There were 0 (zero) sites repeated this month.
paste(repeats, collapse = ", ") 会把站点编号拼成一个字符串,并指定列表的分隔方式。
注意计数和站点编号的区别
不要为了输出零而把空的 repeats 改成 0。这样向量就包含了一个元素,后续使用 length() 或 n_distinct() 统计时会得到 1,还可能把 0 当作站点编号。
上述示例按不同 SiteId 统计站点数,因此先使用 unique()。如果直接对未经去重的 repeats 使用 length(),得到的是匹配记录数;当同一 SiteId 有多条记录时,两者可能不同。
另外,%in% 已经返回逻辑向量,不需要再与字符串 'TRUE' 比较。原来的位置筛选可以简化为 which(match),也可以像上面的代码一样直接用逻辑向量筛选。筛选结果保留 this_month 中的顺序,所以题目第一组数据得到的是 102, 104。
备注:内容仅供参考。
