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