将字符菌落形成单位转换为 R 中的数字科学记数法
Convert character colony-forming units to numeric scientific notation in R
假设我有以下特征向量,其中包含特定细菌物种的菌落形成单位数据
head(data$bacteria)
[1] "3*10^5" "2*10^6" "10^4" "7*10^7" "3*10^6" "2*10^7"
我希望具有这些算术的 chr 向量是一个向量,该向量具有以科学记数法表示的该算术表达式的数值结果,以便我可以 运行 进行一些统计测试
我尝试使用 as.numeric
但它将数据强制转换为 NAs
as.numeric(data$bacteria)
NAs introduced by coercion [1] NA NA NA NA NA NA...
如何在不丢失信息的情况下将具有数学表达式的字符向量转换为这些表达式的科学记数法的数值结果?
您可以使用包 stringr 来迭代替换导致转换为数字失败的组件。
请看下面的代码。
library(stringr)
a <- c("3*10^5", "2*10^6", "10^4", "7*10^7", "3*10^6", "2*10^7")
# this replaces the string "*10^"
b <- str_replace( a, "\*10\^", "e")
# now we still miss those occurrences which do not start with a digit and "*"
c <- str_replace( b, "10\^", "1e")
d <- as.numeric(c)
d
#> [1] 3e+05 2e+06 1e+04 7e+07 3e+06 2e+07
class(d)
#> [1] "numeric"
由 reprex package (v1.0.0)
于 2021-03-03 创建
您可以使用:
sapply(data$bacteria, function(x) eval(parse(text = x)), USE.NAMES = FALSE)
例如-
x1 <- c("3*10^5" ,"2*10^6", "10^4", "7*10^7","3*10^6", "2*10^7")
sapply(x1, function(x) eval(parse(text = x)), USE.NAMES = FALSE)
#[1] 3e+05 2e+06 1e+04 7e+07 3e+06 2e+07
假设我有以下特征向量,其中包含特定细菌物种的菌落形成单位数据
head(data$bacteria)
[1] "3*10^5" "2*10^6" "10^4" "7*10^7" "3*10^6" "2*10^7"
我希望具有这些算术的 chr 向量是一个向量,该向量具有以科学记数法表示的该算术表达式的数值结果,以便我可以 运行 进行一些统计测试
我尝试使用 as.numeric
但它将数据强制转换为 NAs
as.numeric(data$bacteria)
NAs introduced by coercion [1] NA NA NA NA NA NA...
如何在不丢失信息的情况下将具有数学表达式的字符向量转换为这些表达式的科学记数法的数值结果?
您可以使用包 stringr 来迭代替换导致转换为数字失败的组件。
请看下面的代码。
library(stringr)
a <- c("3*10^5", "2*10^6", "10^4", "7*10^7", "3*10^6", "2*10^7")
# this replaces the string "*10^"
b <- str_replace( a, "\*10\^", "e")
# now we still miss those occurrences which do not start with a digit and "*"
c <- str_replace( b, "10\^", "1e")
d <- as.numeric(c)
d
#> [1] 3e+05 2e+06 1e+04 7e+07 3e+06 2e+07
class(d)
#> [1] "numeric"
由 reprex package (v1.0.0)
于 2021-03-03 创建您可以使用:
sapply(data$bacteria, function(x) eval(parse(text = x)), USE.NAMES = FALSE)
例如-
x1 <- c("3*10^5" ,"2*10^6", "10^4", "7*10^7","3*10^6", "2*10^7")
sapply(x1, function(x) eval(parse(text = x)), USE.NAMES = FALSE)
#[1] 3e+05 2e+06 1e+04 7e+07 3e+06 2e+07