R:带有标记化功能的自创建函数,%like%仅在第一个标记上起作用

问题描述 投票:0回答:1

我有两列的数据帧,第二列(单元)主要包含第一列(str)的第一个单词。请在下面查看:

> df <- data.frame(str = c("cups vegetable soup", "cup brown lentils", "carrot", "stalks celery"), unit = c("cups", "cup", NA, "stalks"), stringsAsFactors = FALSE)

> df
                  str   unit
1 cups vegetable soup   cups
2   cup brown lentils    cup
3              carrot   <NA>
4       stalks celery stalks

如果$ str的第一个单词与$ unit上的对应值(在同一行上)匹配,我想擦除它。

为此,我创建了如下所示的函数“ DelFunction”:

 DelFunction <- function(x, y) {
  tokens_x <- x[[1]]
  tokens_y <- y[[1]]
  if ((tokens_x %like% tokens_y) == TRUE) {
    regmatches(tokens_x, regexpr("[a-z]+", tokens_x)) <- ""
  }
  tokens_x
}

此后,我在相应的行上使用了sapply

df$str<- sapply(df$str, DelFunction, df$unit)

我得到以下结果,您将看到,该代码仅适用于第一行,其中删除了“ cups”一词。

> df
                str   unit
1    vegetable soup   cups
2 cup brown lentils    cup
3            carrot   <NA>
4     stalks celery stalks

目标是获得以下结果

> df
                str   unit
1    vegetable soup   cups
2    brown lentils    cup
3            carrot   <NA>
4             celery stalks

有人知道如何解决该问题吗?

谢谢!

我有两列的数据帧,第二列(单元)主要包含第一列(str)的第一个单词。请在下面查看:> df

r function dataframe comparison tokenize
1个回答
0
投票
library(stringr)
library(dplyr, warn.conflicts = FALSE)

df <-
  data.frame(
    str = c(
      "cups vegetable soup",
      "cup brown lentils",
      "carrot",
      "stalks celery"
    ),
    unit = c("cups", "cup", NA, "stalks"),
    stringsAsFactors = FALSE
  )

df %>%
  mutate(str = trimws(str_replace(str, unit, ''))) %>%
  mutate(str = if_else(is.na(unit), df$str, str)) -> df2

df2
#>              str   unit
#> 1 vegetable soup   cups
#> 2  brown lentils    cup
#> 3         carrot   <NA>
#> 4         celery stalks
© www.soinside.com 2019 - 2024. All rights reserved.