【发布时间】:2022-02-02 19:55:11
【问题描述】:
数据是这样的:
示例 - 数据库名称
detail - 第一列包含带有数字的字符串(数字可以附加到 $ 等,例如 25m$,也可以是十进制,例如 1.2m$ 或 $1.2M)
假设数据表如下所示:
example$detail<- c("The cole mine market worth every year 100M$ and the equipment they use worth 30$m per capita", "In 2017 the first enterpenur realized there is a potential of 500$M in cole mining", "The cole can make 23b$ per year ans help 1000000 familys living on it")
我想在示例数据表中添加一列 - 名为:“number”,它将提取“detail”列中字符串中的第一个数字。但是如果这个数字等于向量“year”中的一个数字(它不在示例数据库中 - 它是我创建的一个单独的列表),我希望它提取字符串 example$detail 的第二个数字。
所以我创建了另一个年份列表(与数据库分开),
years<-c(2016:2030 )
我正在尝试创建新列 - 编号
到目前为止我做了什么: 通过编写以下命令,我设法添加了提取字符串第一个数字的变量:
example$number<-as.integer( sub("\\D*(\\d+).*", "\\1", example$detail) ) # EXTRACT ONLT INTEGERS
example$number1<-format(round(as.numeric(str_extract(example$detail, "\\d+\\.*\\d*")), 2), nsmall = 2) #EXTRACT THE NUMBERS AS DECIMALS WITH TWO DIGITS AFTER THE . (ITS ENOUGH FOR ME)
example$number1<-ifelse(example$number %in% years, TRUE, example$number1 ) #IF THE FIRST NUMBER EXTRACTED ARE IN THE YEARS VECTOR RETURN "TRUE"
然后我尝试编写一个代码,根据这个提取第二个数字,如果它不起作用,只是返回错误
我试过了:
gsub("[^\d]*[\d]+[^\d]+([\d]+)", example$detail)
str_extract(example$detail, "\d+(?=[A-Z\s.]+$)",[[2]])
as.integer( sub("\\D*(\\d+).*", "\\1", example$detail) )
as.numeric(strsplit(example$detail, "\\D+")[1])
我不明白我如何符号化任何数字(整数\数字)或如何符号化字符串中的第二个数字。
非常感谢!!
【问题讨论】:
-
请用缩进格式化代码
-
请提供足够的代码,以便其他人更好地理解或重现问题。
标签: r integer decimal data-extraction