[英]R dplyr - select values from one column based on position of a specific value in another column
[英]r, dplyr: how to transform values in one column based on value in another column using gsub
我有一個具有兩個(相關)因素的 dataframe,我想從另一個因素的值中刪除一個等於一個因素的 substring,或者如果沒有這樣的 substring,則不理會它。 我可以使用dplyr
做到這一點嗎?
要制作 MWE,假設這些因素是x
和y
。
library(dplyr)
df <- data.frame(x = c(rep('abc', 3)), y = c('a', 'b', 'd'))
df
:
x y
1 abc a
2 abc b
3 abc d
我想要的是:
x y
1 bc a
2 ac b
3 abc d
我的嘗試是:
df |> transform(x = gsub(y, '', x))
但是,這會產生以下不正確的結果以及警告消息:
x y
1 bc a
2 bc b
3 bc d
Warning message:
In gsub(y, "", x) :
argument 'pattern' has length > 1 and only the first element will be used
我怎樣才能做到這一點?
str_remove
針對pattern
而不是gsub
進行矢量化
library(stringr)
library(dplyr)
df <- df %>%
mutate(x = str_remove(x, y))
-輸出
df
x y
1 bc a
2 ac b
3 abc d
如果我們想使用sub/gsub
,那么可能需要rowwise
df %>%
rowwise %>%
mutate(x = sub(y, "", x)) %>%
ungroup
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.