简体   繁体   English

如何使用dplyr和stringr替换特定列中的每一行的字符串

[英]How to replace string for every row in specfic column using dplyr and stringr

I have the following tibble: 我有以下问题:


library(tidyverse)

df <- tibble::tribble(
  ~sample, ~colB, ~colC,
  "foo",   1,  2,
  "bar_x",   2,  3,
  "qux.6hr.ID",   3,  4,
  "dog",   1,  1
)


df
#> # A tibble: 4 x 3
#>       sample  colB  colC
#>        <chr> <dbl> <dbl>
#> 1        foo     1     2
#> 2      bar_x     2     3
#> 3 qux.6hr.ID     3     4
#> 4        dog     1     1

df <- factor(final_df$samples, levels=c("bar_x","foo","qux.6hr.ID","dog"))

    df
#> [1] foo        bar_x      qux.6hr.ID dog       
#> Levels: bar_x foo qux.6hr.ID dog

What I want to do is for every row in sample column remove these substrings: _x and .6hr if exist. 我要为sample列中的每一行删除以下子字符串: _x.6hr如果存在)。 The final table looks like this: 决赛桌看起来像这样:

     sample  colB  colC
        foo     1     2
        bar     2     3
     qux.ID     3     4
        dog     1     1

How can I achieve that? 我该如何实现?

We can use 我们可以用

df %>% 
     mutate(sample = gsub("_x|\\.\\d+[A-Za-z]+", "", sample))
# A tibble: 4 x 3 
#   sample  colB  colC
#    <chr> <dbl> <dbl>
#1    foo     1     2
#2    bar     2     3
#3 qux.ID     3     4
#4    dog     1     1

If the 'sample' column is factor class either we can wrap with factor on the output of gsub or do this on the levels of sample 如果“样本”列是factor类,我们可以在gsub的输出中用factor包装,也可以在样本levels上进行

levels(df$sample) <- gsub("_x|\\.\\d+[A-Za-z]+", "", levels(df$sample))
df$sample
#[1] foo    bar    qux.ID dog   
#Levels: bar foo qux.ID dog

暂无
暂无

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

相关问题 如何使用dplyr stringr删除列中每一行括号内的所有内容 - How to remove everything within brackets for every row in a column using dplyr stringr 如何使用 stringr 函数替换精确的字符串? - How to replace an exact string using stringr functions? 使用dplyr和stringr替换所有值以 - Using dplyr and stringr to replace all values starts with 如何使用stringr库删除列中的部分字符串值? - How to remove part of string value in column using stringr library? 为什么stringr :: str_replace()将字符串中的每个字符都匹配为“。”? - Why does stringr::str_replace() match every character in a string as “.”? 如何在`dplyr`管道中使用`stringr` - How to use `stringr` in `dplyr` pipe 如何根据该列的值中是否存在字符串来替换该列中某些索引处的值(使用 dplyr 并重复无循环)? - How to replace values at certain indices in a column based on presence of a string in values of that column (using dplyr and repeatedly with no loop)? 如何使用 stringr 将括号内最后出现的字符串与列字符串提取到另一列中? - How do I extract the last occurring string within a parentheses with a column string into another column using stringr? 如何在列的每一行中替换一个字符 - How to replace one character in every row of a column 如何使用 R、stringr 等动态删除或替换字符串中具有不确定数字的单词? - How to dynamically remove or replace words with uncertain numbers in a string using R, stringr etc?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM