从字符串中提取整数值

时间:2017-07-28 13:12:17

标签: r

我在变量中保存了"RADIANCE_MULT_BAND_1 = 1.2412E-02"形式的字符。我想将整数值提取为0.012412。请在R。

中建议这样做的语法

1 个答案:

答案 0 :(得分:0)

# function to extract number from a string
f = function(x) {
y = unlist(strsplit(x, " "))
y = as.numeric(y)
y = y[!is.na(y)]
y }


# having one value
x = "RADIANCE_MULT_BAND_1 = 1.2412E-02"

f(x)

# [1] 0.012412


# having multiple values
dt = data.frame(x = c("RADIANCE_MULT_BAND_1 = 1.2412E-02",
                      "RADIANCE_MULT_BAND_2 = 1.5412E-02",
                      "RADIANCE_MULT_BAND_3 = 2.2412E-02"), stringsAsFactors = F)

dt$value = f(dt$x)

dt

#                                   x    value
# 1 RADIANCE_MULT_BAND_1 = 1.2412E-02 0.012412
# 2 RADIANCE_MULT_BAND_2 = 1.5412E-02 0.015412
# 3 RADIANCE_MULT_BAND_3 = 2.2412E-02 0.022412