【问题标题】:How to replace string for every row in specfic column using dplyr and stringr如何使用 dplyr 和 stringr 替换特定列中每一行的字符串
【发布时间】:2017-11-04 13:07:31
【问题描述】:

我有以下小标题:


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

我想要对sample 列中的每一行删除这些子字符串:_x.6hr(如果存在)。决赛桌长这样:

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

我怎样才能做到这一点?

【问题讨论】:

  • df %&gt;% mutate(sample = gsub('_x|\\.6hr', '', sample)) 或等效于 stringr,df %&gt;% mutate(sample = str_replace_all(sample, '_x|\\.6hr', ''))
  • @alistaire 实际上我的 df 包含因子。看我的更新。对不起。如何修改您的代码?
  • gsub 仍然有效,尽管它会强制转换为字符。你可以打电话给levels&lt;-,但是在 dplyr 语法上有点尴尬。 forcats 包提供了另一种选择:df %&gt;% mutate(sample = factor(sample), sample = forcats::fct_relabel(sample, function(x){str_replace_all(x, '_x|\\.6hr', '')})) 尽管您必须将第二个参数构造为函数 à la lapply

标签: r regex dplyr stringr tidyverse


【解决方案1】:

我们可以使用

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

如果“样本”列是 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

【讨论】:

  • 其实我的 df 包含因子。看我的更新。对不起。如何修改您的代码?
  • @pdubois gsub 也将采用 factor。如果您保留为factor,则使用factor 包装输出,即mutate(sample = factor(gsub(..
【解决方案2】:

这里有一个使用 purrr:map 函数的解决方案,它的额外好处是无论“sample”是 chr 还是 factor 都返回相同的结果。

df %>%
   mutate(sample = map_chr(sample, ~str_replace(.x, 
                                         pattern = "_x|\\.\\d+[A-Za-z]+", 
                                         replacement = "")))
# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 2023-02-23
    • 2019-11-14
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多