简体   繁体   English

r、dplyr:如何使用 gsub 根据另一列中的值转换一列中的值

[英]r, dplyr: how to transform values in one column based on value in another column using gsub

I have a dataframe with two (relevant) factors, and I'd like to remove a substring equal to one factor from the value of the other factor, or leave it alone if there is no such substring.我有一个具有两个(相关)因素的 dataframe,我想从另一个因素的值中删除一个等于一个因素的 substring,或者如果没有这样的 substring,则不理会它。 Can I do this using dplyr ?我可以使用dplyr做到这一点吗?

To make a MWE, suppose these factors are x and y .要制作 MWE,假设这些因素是xy

library(dplyr)
df <- data.frame(x = c(rep('abc', 3)), y = c('a', 'b', 'd'))

df : df

      x y
1   abc a
2   abc b
3   abc d

What I want:我想要的是:

      x y
1    bc a
2    ac b
3   abc d

My attempt was:我的尝试是:

df |> transform(x = gsub(y, '', x))

However, this produces the following, incorrect result, plus a warning message:但是,这会产生以下不正确的结果以及警告消息:

    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

How can I do this?我怎样才能做到这一点?

str_remove is vectorized for the pattern instead of gsub str_remove针对pattern而不是gsub进行矢量化

library(stringr)
library(dplyr)
df <- df %>% 
    mutate(x = str_remove(x, y))

-output -输出

df
    x y
1  bc a
2  ac b
3 abc d

If we want to use sub/gsub , then may need rowwise如果我们想使用sub/gsub ,那么可能需要rowwise

df %>%
   rowwise %>%
   mutate(x = sub(y, "", x)) %>%
   ungroup

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R dplyr-根据特定值在另一列中的位置从一列中选择值 - R dplyr - select values from one column based on position of a specific value in another column 在 R dplyr 中,gsub() 在 mutate() 中使用列作为模式 - In R dplyr, gsub() in mutate() using column as the pattern 有没有办法在 R 中使用 dplyr 根据另一个列的值创建一个新列? - Is there a way to create a new column based on the values of another one using dplyr in R? 如何使用dplyr根据另一列中的字符值的一部分更新列值? - how to renew column values based on part of character value in another column using dplyr? 使用dplyr基于列值对R中的值求和 - Summing values in R based on column value with dplyr 用 R dplyr 中另一列的值替换一列的值 - Replace the values of one column with values of another column in R dplyr 在R中根据值以及另一列的频率使用dplyr创建列 - Create column with dplyr based on value and also frequency of another column, in R R dplyr根据乐趣指数汇总一个列值(另一列) - R dplyr summarise one column value based on index of fun(another column) 如何使用 dplyr 创建基于另一个值的列,而不必写下每个值? - How do I create a column based on values of another using dplyr without having to write down every value? R - 基于使用另一列的函数为一列添加值 - R - adding values for one column based on a function using another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM