删除R中列的最后一个下划线之后的所有内容 [英] remove everything after the last underscore of a column in R
本文介绍了删除R中列的最后一个下划线之后的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,对于一个特定的列,我想删除最后一个下划线之后的所有内容.
I have a dataframe and for a particular column I want to strip out everything after the last underscore.
所以:
test <- data.frame(label=c('test_test_test', 'test_tom_cat', 'tset_eat_food', 'tisk - tisk'),
stuff=c('blah', 'blag', 'gah', 'nah') ,
numbers=c(1,2,3, 4))
应该成为
result <- data.frame(label=c('test_test', 'test_tom', 'tset_eat', 'tisk - tisk'),
stuff=c('blah', 'blag', 'gah', 'nah') ,
numbers=c(1,2,3, 4))
我有:
require(dplyr)
test %>%
mutate(label = gsub('_.*','',label))
但这会删除第一个下划线的所有内容,并给我
but that drops everything from the first underscore and gives me
wrong_result <- data.frame(label=c('test', 'test', 'tset', 'tisk - tisk'),
stuff=c('blah', 'blag', 'gah', 'nah') ,
numbers=c(1,2,3, 4))
推荐答案
我们可以使用 sub
,并且无需任何外部程序包即可
We can use sub
and this can be done without any external packages
test$label <- sub("_[^_]+$", "", test$label)
test$label
#[1] "test_test" "test_tom" "tset_eat" "tisk - tisk"
这篇关于删除R中列的最后一个下划线之后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文