这不会赢得任何选美比赛,但您绝对可以结合使用cut 和一些字符串处理来创建您自己的分组stem 函数。
这是一个示例函数,已注释,因此您可以扩展它以满足您的实际需求:
grouped_stem <- function(invec, n = 3) {
# Sequence of lowest tens and highest tens in the input data, by 10
cuts <- seq((min(invec) %/% 10) * 10, round(max(invec), -(nchar(max(invec))-1)), 10)
# For pretty labels in `cut`
labs <- sub("(.*).$", "\\1", cuts)
labs <- replace(labs, !nzchar(labs), "0")
# List of the values according to their `cut` intervals
temp <- split(invec, cut(invec, cuts, labs[-length(labs)], right = FALSE))
# Only interested in the last digit
temp <- relist(sub(".*(.)$", "\\1", unlist(temp, use.names = FALSE)), temp)
# Paste the values together. Add in a "*" that we can get rid of later if not required
combined <- vapply(temp, function(y) sprintf("%s*", paste(y, collapse = "")), character(1L))
# Split by number of groups of tens per stem
splits <- split(combined, ((seq_along(combined)-1) %/% n))
# Construct the stems and leaves
stems <- vapply(splits, function(x) {
paste(names(x)[1], names(x)[length(x)], sep = " to ")
}, character(1L))
leaves <- vapply(splits, function(x) {
sub("[*]$", "", paste(x, sep = "", collapse = ""))
}, character(1L))
# Print and store
cat(sprintf(sprintf("%%%ss | %%s", max(nchar(stems))+2), stems, leaves), sep = "\n")
invisible(setNames(as.list(leaves), stems))
}
在您的示例数据上运行,它会产生:
grouped_stem(data)
## 0 to 2 | 67*179*26
## 3 to 5 | 2478*15699*368
## 6 to 8 | 24457**56