繁体   English   中英

如何将 R 中存储为 char 的指数转换为数字?

[英]How do I convert to numeric an exponential stored as a char in R?

我有一个文件,其中的科学记数法存储为 0.00684*10^0.0023。 当我用 read.csv() 读取文件时,它们被加载为字符串,并尝试用 as.numeric() function 转换它们只返回 NA。

a = "0.00684*10^0.0023"

as.numeric(a)

NA

有没有办法强制 R 将变量作为科学计数法?

这里有几种方法。 他们使用问题中的a (也在下面的注释中显示)或c(a, a)来说明如何将其应用于向量。 没有使用包。

1)使用评估/解析:

eval(parse(text = a))
## [1] 0.00687632

或者对于诸如c(a, a)的向量

sapply(c(a, a), function(x) eval(parse(text = x)), USE.NAMES = FALSE)
## [1] 0.00687632 0.00687632

2)另一种方法是将输入拆分并自己计算。

with(read.table(text = sub("\\*10\\^", " ", c(a, a))), V1 * 10^V2)
## [1] 0.00687632 0.00687632

3)第三种方法是转换为复数,将实部和虚部结合起来得到结果。

tmp <- type.convert(sub("\\*10\\^(.*)", "+\\1i", c(a, a)), as.is = TRUE)
Re(tmp) * 10^Im(tmp)
## [1] 0.00687632 0.00687632

4)另一种拆分方法是:

as.numeric(sub("\\*.*", "", c(a, a))) * 
  10^as.numeric(sub(".*\\^", "", c(a, a)))
## [1] 0.00687632 0.00687632

6)我们可以使用上面的任何一个来定义一个自定义的 class,它可以读取所需表单的字段。 首先我们写出一个测试数据文件,然后定义一个自定义的num class。在read.csv使用colClasses参数指定每一列有哪个class。 将 NA 用于我们想要读取的那些列read.csv自动确定 class..

# generate test file
cat("a,b\n1,0.00684*10^0.0023\n", file = "tmpfile.csv")

setAs("character", "num",
 function(from) with(read.table(text = sub("\\*10\\^", " ", from)), V1 * 10^V2))

read.csv("tmpfile.csv", colClasses = c(NA, "num"))
##   a          b
## 1 1 0.00687632

有了这个定义,我们也可以as这样使用:

as(c(a, a), "num")
## [1] 0.00687632 0.00687632

笔记

a <- "0.00684*10^0.0023"

一个想法:

library(stringr)
a <- "0.00684*10^0.0023" # your input
b <- str_split(a, "\\*10\\^") # split the string by the operator
b <- as.numeric(b[[1]]) # transform the individual elements to numbers

c <- b[1]*10^(b[2]) # execute the wished operation with the obtained numbers
c # the result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM