【问题标题】:How to extract numbers from a string column and determine whether they are less than a threshold?如何从字符串列中提取数字并确定它们是否小于阈值?
【发布时间】:2020-12-01 01:05:12
【问题描述】:

所以我有以下df:

df=data.frame(strength=c("10MG;50MG","2MG;5MG","1MG,5MG","100MG;1UG"))

我想标记

library(dplyr)    
df %>% mutate(new=as.numeric(unlist(str_extract_all(strength, "[0-9]+"))),check=any(which(new<5)))

【问题讨论】:

  • 类似df$new &lt;- stringr::str_detect(df$strength, "(?&lt;!\\d)[1-4]MG\\b")?
  • @WiktorStribiżew,为什么 str_extract_all 在这种情况下不起作用?在我检查之前我需要将其他单位转换为MG

标签: r regex string dplyr stringr


【解决方案1】:

str_extract_all 返回一个列表,因此如果您unlist 他们,您将丢失有关哪个值来自哪一行的信息。将它们保存在一个列表中,然后使用rowwisemap 函数之一遍历每个列表以检查该行中any 的值是否小于5。

library(dplyr)

df %>% 
  mutate(new = stringr::str_extract_all(strength, "[0-9]+")) %>%
  rowwise() %>%
  mutate(check = any(as.numeric(new) < 5))

# strength  new       check
#  <chr>     <list>    <lgl>
#1 10MG;50MG <chr [2]> FALSE
#2 2MG;5MG   <chr [2]> TRUE 
#3 1MG,5MG   <chr [2]> TRUE 
#4 100MG;1UG <chr [2]> TRUE 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 2016-10-06
    • 2018-07-30
    • 2015-06-25
    • 2022-10-16
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多