我需要验证许多茎叶图的摘要统计量(均值,标准差等),因此我已经编写了一些函数尝试将茎叶图转换为向量,因为从R中的向量中获取统计信息很容易。

可以将茎叶图作为矩阵或数据框输入,其中每一行都是一个字符串。 “|”符号表示小数点后的分隔符。例如,下面的茎叶图

100 | 9
102 | 601
104 | 0678
106 | 5
108 | 649
110 | 3857
112 | 56
114 | 29

可以输入为
> example.stem = rbind("100|9", "102|601", "104|0678", "106|5", "108|649", "110|3857", "112|56", "114|29")

我执行此茎叶图转换的两个函数是
## Convert a single row into a vector
> convert.row = function(current){

  temp.split = as.vector(strsplit(current, split="|", fixed=TRUE)[[1]])

  int = temp.split[1]

  dec = temp.split[2]
  dec = (strsplit(dec, ""))[[1]]

  temp.string = NULL

  for(i in 1:length(dec)){
    temp.string[i] = paste(int, dec[i], sep=".")
  }

  result = as.numeric(temp.string)
  return(result)
  }


## Convert matrix or dataframe with a stem and leaf plot into a vector
> stem.to.vec = function(df){

  df = data.frame(df, stringsAsFactors = F)

  result.vec = NULL

  for(i in 1:nrow(df)){
    current = df[i, ]
    result.vec = c(result.vec, convert.row(current))
  }

  return(result.vec)
  }

我们可以验证此方法是否有效,因为我们知道解决方案:
> solution = c(100.9, 102.6,102.0,102.1,104.0,104.6,104.7,104.8,106.5,108.6,108.4,108.9,110.3,110.8,110.5,110.7,112.5,112.6, 114.2, 114.9)
> stem.to.vec(example.stem) == solution

尽管此解决方案有效,但它并不优雅或高效。我们正在将具有字符串的矩阵/数据帧转换为数值,然后再转换为字符串,然后再次转换为数值。因此,对于非常大的茎叶图而言,工作可能会很慢。

谁能提出一个转换次数更少,更好,更有效的解决方案?

最佳答案

这远非完美,但我认为您还是必须进行一些来回转换。

使用read.table吸收数据,然后将右侧除以10,并添加到左侧的每个值。

out <- read.table(text=example.stem, sep="|", colClasses=c("numeric","character"))
res <- unlist(Map(`+`, out$V1, lapply(strsplit(out$V2,""), function(x) as.numeric(x)/10)))
res
# [1] 100.9 102.6 102.0 102.1 104.0 104.6 104.7 104.8 106.5 108.6 108.4 108.9
# [13] 110.3 110.8 110.5 110.7 112.5 112.6 114.2 114.9

identical(solution,res)
#[1] TRUE

关于r - 有效地将茎和叶转换为R中的向量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50689026/

10-12 00:28
查看更多