【问题标题】:Grouping of Stem- Leaf plot in RR中的茎叶图分组
【发布时间】:2020-05-27 13:26:10
【问题描述】:

我有一个茎叶图作为问题,如下所示:

0 | 6
1 | 179
2 | 26
3 | 2478
4 | 15699
5 | 368
6 | 24457
7 | 
8 | 56

所以,我自己创建了一个向量,它将创建一个与上述相同的茎图。

data <- c(06,11,17,19,22,26,32,34,37,38,41,45,46,49,49,53,56,58,62,64,64,65,67,7,85,86)

我要做的是,我需要将茎按 2 分组,然后使用 R 绘制相应的茎图。

解决方案看起来有点像这样:

0-2|6*179*26
3-5|2478*15699*368
6-8|244457**56

“*”用于分隔组中每个茎的叶子。即对于组茎0-2,表示第一行的叶子6对应茎0;叶 1,7 和 9 对应于茎 1,叶 2 和 6 对应于茎 2。

我发现stem()没有用,所以想用“interval”函数将数据除以2,然后构建一个用户定义的函数,但结果却给了我相同的stem值。

有没有办法通过使用内置函数/通过用户定义来获得所需的解决方案? 非常感谢提前。!!

【问题讨论】:

    标签: r dataframe plot sapply


    【解决方案1】:

    这不会赢得任何选美比赛,但您绝对可以结合使用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
    

    【讨论】:

    • 请注意,理想情况下,您可能希望将格式设置(在cat 行中完成)留给自定义的print 方法...
    • 感谢您解决问题并解释代码行!!!
    • 这很快就被破解了,并不完全准确,尤其是负数。这是一个更好的版本:gist.github.com/mrdwab/e48cf0c22d038e00237b57bf7cc1211e
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多