gpt4 book ai didi

r - 有效地将茎和叶转换为 R 中的向量

转载 作者:行者123 更新时间:2023-12-01 16:15:59 25 4
gpt4 key购买 nike

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

茎叶图可以输入为矩阵或数据框,其中每一行都是一个字符串。 “|” symbol 代表小数位的分隔符。比如下面的茎叶图

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com