正则表达式有效,但不适用于我的向量中的字符串

Regex works, but not on strings in my vector

所以我尝试使用 grep 查找模式并替换我的单列数据框中的值。我基本上想要说 "delete everything after the comma until the end of the string" 的 grep。 我写了表达式,它适用于我的虚拟向量:

> library(stringr)
> pretendvector <- c("Hi","Hi,there","Hi there, how are you")
>str_replace(pretendvector, regex(',.*$'),'')
[1] "Hi"       "Hi"       "Hi there"

但是,当对我的向量应用相同的表达式时(因为它是 stringr,我将数据帧的列向量化),它 returns 列中的每个值,并且不应用该表达式。有谁知道为什么会这样?

我猜 OP 没有将 str_replace 的输出分配给新对象或更新原始向量。那样的话,

newvector <- str_replace(pretendvector, regex(',.*$'),'') 

我们也可以使用 base R

中的 sub 来做到这一点
newvector <- sub(",.*", "", pretendvector)