簡體   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