基础 R 解决方案:
# Solution 1, string split, unlist, coerce to numeric, subset out NAs, coerce to numeric,
# format with scientific notation (type coercion to string):
format(as.numeric(na.omit(as.numeric(unlist(strsplit(X, "="))))), scientific = TRUE)
# Solution 2, substitution of alphabetic characters coercion to numeric
# format with scientific notation (type coercion to string)
format(as.numeric(gsub("[^0-9]+", "", X)), scientific = TRUE)
# Solution 3, string split, digit extraction:
grep("\\d+", unlist(strsplit(X, "=")), value = TRUE)
数据:
X <- as.character("reflectance_scales=5.011129178e-05")
基准测试:
# Install pacakges if they are not already installed:
necessary_packages <- c("bench")
# Create a vector containing the names of any packages needing installation:
new_packages <- necessary_packages[!(necessary_packages %in% installed.packages()[,"Package"])]
# If the vector has more than 0 values, install the new pacakges
# (and their) associated dependencies:
if(length(new_packages) > 0){
install.packages(new_packages, dependencies = TRUE)
}
# Initialise the packages in the session:
lapply(necessary_packages, require, character.only = TRUE)
# Benchmark the solutions:
function_performance <- bench::mark(
# Solution 1, string split, unlist, coerce to numeric, subset out NAs, coerce to numeric,
# format with scientific notation (type coercion to string):
format(as.numeric(na.omit(as.numeric(unlist(strsplit(X, "="))))), scientific = TRUE),
# Solution 2, substitution of alphabetic characters coercion to numeric
# format with scientific notation (type coercion to string)
format(as.numeric(gsub("[^0-9]+", "", X)), scientific = TRUE),
# Solution 3, string split, digit extraction:
grep("\\d+", unlist(strsplit(X, "=")), value = TRUE),
check = FALSE)
# Check the function performance:
View(function_performance)