【问题标题】:How can I change columns with mutate(across()) due to a specific RegEx?由于特定的正则表达式,如何使用 mutate(across()) 更改列?
【发布时间】:2021-01-18 09:29:05
【问题描述】:

我对 mutate(across()) 函数有疑问。 在您可以在下面看到的 tibble 中,我想删除列中的“字母 + 下划线”(例如“p__”、“c__”等)。

A tibble: 2,477 x 4
   Phylum                Class                   Order               Family                 
   <chr>                 <chr>                   <chr>               <chr>                  
 1 " p__Proteobacteria"  " c__Gammaproteobacter~ " o__Aeromonadales" " f__Aeromonadaceae"   
 2 " p__Bacteroidota"    " c__Bacteroidia"       " o__Bacteroidales" " f__Williamwhitmaniac~
 3 " p__Fusobacteriota"  " c__Fusobacteriia"     " o__Fusobacterial~ " f__Leptotrichiaceae" 
 4 " p__Firmicutes"      " c__Clostridia"        " o__Clostridiales" " f__Clostridiaceae"   
 5 " p__Proteobacteria"  " c__Gammaproteobacter~ " o__Enterobactera~ " f__Enterobacteriacea~
 6 " p__Bacteroidota"    " c__Bacteroidia"       " o__Bacteroidales" " f__Williamwhitmaniac~
 7 " p__Firmicutes"      " c__Clostridia"        " o__Lachnospirale~ " f__Lachnospiraceae"  
 8 " p__Bacteroidota"    " c__Bacteroidia"       " o__Cytophagales"  " f__Spirosomaceae"    
 9 " p__Proteobacteria"  " c__Gammaproteobacter~ " o__Burkholderial~ " f__Comamonadaceae"   
10 " p__Actinobacteriot~ " c__Actinobacteria"    " o__Frankiales"    " f__Sporichthyaceae"  
# ... with 2,467 more rows

一年前我用过这个命令

table <- table %>% 
  mutate_at(vars(Phylum, Class, Order, Family),funs(sub(pattern = "^([a-z])(_{2})", replacement = "", .)))

现在,它提示我不再支持 funs 功能并且它不再工作了。 你对我有什么建议吗? 我想了想:

taxon <- c("Phylum", "Class", "Order", "Family")
table <- table %>% 
  mutate(across(taxon), gsub(pattern = "^([a-z])(_{2})", replacement = "", .))

但在这里我得到了错误:

Error: Invalid index: out of bounds

非常感谢 :) 凯瑟琳

【问题讨论】:

    标签: r dplyr across


    【解决方案1】:

    你可以这样做:

    library(dplyr)
    
    taxon <- c("Phylum", "Class", "Order", "Family")
    table <- table %>%  mutate(across(taxon, 
              ~gsub(pattern = "^([a-z])(_{2})", replacement = "", .)))
    

    我没有你的数据来确认这一点,但字符串的开头似乎有一个空格,应该首先删除。

    table <- table %>%  mutate(across(taxon, 
               ~gsub(pattern = "^([a-z])(_{2})", replacement = "", trimws(.))))
    

    【讨论】:

    • 最后一个命令成功了,完美!谢谢 :) 只是一个问题我的理解,为什么我必须写 ~gsub 而不是单独写 gsub?
    • 这是基于公式的语法,用于在across 中应用函数。另一种方法是使用匿名函数,它将最后一部分更改为function(x) gsub(pattern = "^([a-z])(_{2})", replacement = "", trimws(x))
    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2021-12-29
    • 2017-11-22
    相关资源
    最近更新 更多