将词干和叶子转换为R中的向量有效

时间:2018-06-04 21:27:29

标签: r performance type-conversion

我需要验证许多茎和叶图的汇总统计(平均值,标准偏差等),所以我写了一些函数来尝试将茎和叶图转换成向量,因为它很容易从向量中获取统计数据在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

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

有人建议使用更少的转换来提供更好,更有效的解决方案吗?

3 个答案:

答案 0 :(得分:3)

这远不是很漂亮,但我认为你无论如何都要做一些来回转换。

使用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

答案 1 :(得分:2)

拆分和粘贴方法:

拆分为列表项,然后拆分列表项的第二个元素。最后将两个向量粘贴到列表项中。

x <- sapply(strsplit(example.stem, "[|]"), 
            function(x) { paste(x[1], unlist(strsplit(x[2], "")), sep= ".") })

as.numeric(unlist(x))                           

# [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

答案 2 :(得分:2)

这是一个嵌套的serviceNumber版本,它将所有组合作为字符串,然后将输出值转换为数字:

lapply