将字符串提取函数包装在 ifelse 语句中

2024-03-14

下面的问题是一个延伸这个问题 https://stackoverflow.com/questions/74135095/adding-a-column-to-the-data-that-looks-for-a-list-of-words-and-adds-them-if-foun.

示例数据

我有示例数据如下:

library(data.table)
example_dat <- fread("var_nam description
      some_var this_is_some_var_kg
      other_var this_is_meters_for_another_var
      extra_var the_price_of_apples
      another_var cost_of_goods_sold")
example_dat$description  <- gsub("_", " ", example_dat$description)

       var_nam                    description
1:    some_var            this is some var kg
2:   other_var this is meters for another var
3:   extra_var            the price of apples
4: another_var             cost of goods sold

vector_of_units <- c("kg", "meters", "var")

以前的解决方案

我首先询问如何在此数据中创建一个单独的列,该列查找向量中列出的某些单位(vector_of_units)。一种选择是使用梅丁的这个答案 https://stackoverflow.com/a/74135271/8071608。这会得到所有匹配项。

library(tidyverse)
setDT(example_dat)[, unit :=    unlist(lapply(example_dat$description,function(x) 
                    paste0(vector_of_units[str_detect(x,vector_of_units)],
                    collapse = ",")))]

       var_nam                    description       unit
1:    some_var            this is some var Kg     kg,var
2:   other_var this is meters for another var meters,var
3:   extra_var            the Price of apples           
4: another_var             cost of goods sold         

我还发现langtang 的回答 https://stackoverflow.com/a/71280592/8071608,它得到了第一场比赛(这实际上在我的情况下更可取):

example_dat[, unit:=stringr::str_extract(description, paste0(vector_of_units,collapse = "|"))]

       var_nam                    description   unit
1:    some_var            this is some var kg    var
2:   other_var this is meters for another var meters
3:   extra_var            the price of apples   <NA>
4: another_var             cost of goods sold   <NA>

基于字符串向量从 data.table 列中提取字符串到新列中 https://stackoverflow.com/questions/71280466/based-on-vector-of-strings-extract-string-from-data-table-column-into-new-column

使用 ifelse 语句更灵活

不过,我希望有更多的灵活性。

首先,我想提供一个匹配向量和一个用于单独粘贴的向量,以便我可以将命中更改为其他内容:

vector_of_units_in <- c("kg", "meters", "var")
vector_of_units_out <- c("kilogram", "meters", "variable")

vector_of_units_euro <- c("cost", "price")
vector_of_units_euro_out <- "euro"

其次,我希望能够选择没有命中时发生的情况。例如,当应用 langtang 的解决方案时,我希望它不要用NA.

我一直在尝试弄乱 langtang 的解决方案:

setDT(example_dat)[, unit := ifelse(!is.na(stringr::str_extract(description, vector_of_units_in)), paste0(vector_of_units_out, collapse = "|"), NA)]

# NA has been replaced by unit, so that it is not overwritten in case of no match
setDT(example_dat)[, unit := ifelse(!is.na(stringr::str_extract(description, vector_of_units_euro)), paste0(vector_of_units_euro_out, collapse = "|"), unit)]

但我以此结束:

       var_nam                    description                     unit
1:    some_var            this is some var kg kilogram|meters|variable
2:   other_var this is meters for another var kilogram|meters|variable
3:   extra_var            the price of apples                     <NA>
4: another_var             cost of goods sold                     <NA>

我应该如何编写这个语法?

所需输出

       var_nam                    description       unit
1:    some_var            this is some var Kg     kilogram
2:   other_var this is meters for another var     meters
3:   extra_var            the Price of apples     euro      
4: another_var             cost of goods sold     euro    

您可以使用命名单位向量和Vectorize grep for outer。在办案中if没有找到匹配项,我们可以抛出NA.

units <- c(kilogram="kg", meters="meters", euro="cost", euro="price", variable='var')

dat[, unit:=apply(outer(units, description, Vectorize(grepl)), 2, \(x) 
                  if (any(x)) names(which(x)) else NA)]
dat
# var_nam                    description              unit
# 1:    some_var            this is some var kg kilogram,variable
# 2:    some_var                   this is some                NA
# 3:   other_var this is meters for another var   meters,variable
# 4:   extra_var            the price of apples              euro
# 5: another_var             cost of goods sold              euro

Data:

dat <- structure(list(var_nam = c("some_var", "some_var", "other_var", 
"extra_var", "another_var"), description = c("this is some var kg", 
"this is some var", "this is meters for another var", "the price of apples", 
"cost of goods sold")), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x558a7b025230>)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串提取函数包装在 ifelse 语句中 的相关文章

随机推荐

  • 如何在WPF中制作模板窗口?

    所以我正在构建一个有很多窗口的应用程序 所有窗口都具有相同的基本布局 主窗口 顶部角落有一个标志 标题栏 底部的状态显示器 窗口特定控件的区域 目前我必须在每个窗口中重新创建这个结构 理想情况下 我希望将此布局编码在一个位置 也许编码到自定
  • 如何使用 kafka 模式管理和 Avro 进行重大更改

    使用 avro 进行 kafka 模式管理为我们提供了向后兼容性的灵活性 但是我们如何处理模式中的重大更改 假设生产者A向消费者C发布消息M 假设消息 M 的方案发生了重大变化 例如 名称字段现在分为名字和姓氏 并且我们有新的方案 M Ne
  • 字符串中的数字以查找该字符串中的 UNIX 字符

    我有一个包含单词和数字的字符串 如下所示 6 ovenbread 我怎样才能读取这个号码 我们称之为i 并找到i这个词的第一个字符 看起来s 0 9 1 2 不起作用 我认为 awk 更容易 它有substr函数 允许您选择第 n 个字母
  • 终止导致设备或资源繁忙的进程:“/dev/ttyUSB0”?

    我使用以下 Python 代码连接到我的 Arduino 板 device glob glob dev ttyUSB 0 time sleep 1 arduino serial Serial device 115200 timeout 5
  • 如何获取或生成 Google Cloud Run 服务的部署 URL

    如何在 CI 环境中以编程方式获取已部署服务的 URL 成功部署后确实会记录 URL 但如果我想以编程方式提取并使用 URL 作为部署后需求的一部分 例如 该怎么办 发布验收测试的 URL 只需使用该标志 format value stat
  • 如何监控Linux上进程的线程数?

    我想监视 Linux 上特定进程使用的线程数 有没有一种简单的方法可以在不影响流程性能的情况下获取此信息 try ps huH p
  • 如何在cx_Oracle和python 2.7中处理unicode数据?

    我在用 Python 2 7 cx Oracle 6 0 2 我在我的代码中做了类似的事情 import cx Oracle connection string s s s 192 168 8 168 1521 xe connection
  • 适用于 Azure Service Fabric 无状态 Web API 应用程序的 Swagger

    我正在开发 Web API 服务并作为微服务托管在 Azure Service Fabric 上 我需要为 API 定义实现 Swagger 并且我可以看到 SwaggerConfig Register 方法在应用程序启动时未调用 所以我无
  • mysql_close 和 pg_close 是否是必需的? [复制]

    这个问题在这里已经有答案了 可能的重复 使用 mysql close https stackoverflow com questions 2065282 using mysql close 是否需要 mysql close 和 pg clo
  • Java HashMap Get 基准测试(JMH 与循环)

    我的最终目标是使用标准 Java 集合作为基线 为多个 Java 原始集合库创建一套全面的基准测试 过去我曾使用循环方法来编写此类微基准 我将要进行基准测试的函数放入循环中并迭代 100 万次以上 以便 jit 有机会预热 我计算循环的总时
  • 如何在Python中使用AutoReg预测时间序列

    我正在尝试仅使用自动回归算法来构建老式模型 我发现它有一个实现statsmodel包裹 我已阅读文档 据我了解 它应该像 ARIMA 一样工作 所以 这是我的代码 import statsmodels api as sm model sm
  • 使用 AND 和 OR 的 C# 谓词生成器

    我有以下课程 public class testClass public string name get set public int id get set public int age get set 和以下代码 var list new
  • 如何在 MySQL 中返回数据透视表输出?

    如果我有一个看起来像这样的 MySQL 表 company name action pagecount Company A PRINT 3 Company A PRINT 2 Company A PRINT 3 Company B EMAI
  • AttributeError:模块“jaxlib.xla_extension”没有属性“PmapFunction”

    有人可以帮我修复在 check not jax transformed f 中的 usr local lib python3 7 dist packages haiku src transform py in check not jax t
  • Ruby Mechanize:点击链接

    在 Mechanize on Ruby 中 我必须为我访问的每个新页面分配一个新变量 例如 page2 page1 link with text gt Continue click page3 page2 link with text gt
  • Cucumber 在一段时间后逐步停止执行

    我的一个测试会等到事件发生Then步 如果测试工作正常 则没有问题 但如果测试失败 即没有触发任何事件 那么它就会挂起 我怎样才能设置超时Cucumber I know JUnit有一个超时参数 您可以在 Test annotation h
  • 使用 Spark SQL 跳过/获取

    如何使用 Spark SQL 实现跳过 获取查询 典型的服务器端网格分页 我在网上搜索过 只能找到非常基本的示例 例如 https databricks training s3 amazonaws com data exploration
  • 使用键盘快捷键聚焦于文本字段

    我有一个 macOS Monterrey 应用程序 其中包含TextField在工具栏上 我用它来搜索我的应用程序上的文本 现在 我正在尝试添加键盘快捷键以专注于TextField 我尝试了下面的代码 添加带有快捷方式的按钮作为测试这是否可
  • 在sqlite不同数据库中触发

    我有 2 个不同的数据库 A 和 B 我需要创建一个触发器 当我在数据库 A 的表 T1 中插入任何条目时 数据库 B 的表 T2 的条目将得到已删除 请给我推荐一个方法 这不可能 在SQLite中 触发器内部的DML只能修改同一数据库的表
  • 将字符串提取函数包装在 ifelse 语句中

    下面的问题是一个延伸这个问题 https stackoverflow com questions 74135095 adding a column to the data that looks for a list of words and