gpt4 book ai didi

r - 使用 grepl 创建基于另一列的列

转载 作者:行者123 更新时间:2023-12-04 01:23:24 26 4
gpt4 key购买 nike

让我们考虑一个包含两列wordstemdf。我想创建一个新列来检查 stem 中的值是否包含在 word 中,以及它前面或后面是否有更多字符。最终结果应该是这样的:

WORD     STEM     NEW
rerun run prefixed
runner run suffixed
run run none
... ... ...

到目前为止,您可以在下面看到我的代码。但是,它不起作用,因为 grepl 表达式应用于 df 的所有行。无论如何,我认为它应该阐明我的想法。

df$new <- ifelse(grepl(paste0('.+', df$stem, '.+'), df$word), 'both',
ifelse(grepl(paste0(df$stem, '.+'), df$word), 'suffixed',
ifelse(grepl(paste0('.+', df$stem), df$word), 'prefixed','none')))

最佳答案

您可以使用 mapply 来在每一行使用 grepl,例如:

ifelse(mapply(grepl, paste0(".+", x$STEM, ".+"), x$WORD), "both",
ifelse(mapply(grepl, paste0(x$STEM, ".+"), x$WORD), "suffixed",
ifelse(mapply(grepl, paste0(".+", x$STEM), x$WORD), "prefixed", "none")))
#"prefixed" "suffixed" "none"

或者使用 startsWithendsWith 并使用子集形式向量:

c("none", "both", "prefixed", "suffixed")[1 + (1 + startsWith(x$WORD, x$STEM) +
2*endsWith(x$WORD, x$STEM)) * (nchar(x$WORD) > nchar(x$STEM) &
mapply(grepl, x$STEM, x$WORD))]
#[1] "suffixed" "prefixed" "none"

关于r - 使用 grepl 创建基于另一列的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62264388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com