2016-11-29 7 views
2

データフレームがあります。特定の列については、最後のアンダースコアの後ろのすべてを削除します。列の最後のアンダースコアの後ろのすべてを削除します。

ので:

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)) 

それは最初のアンダースコアからすべてを落とし、

wrong_result <- data.frame(label=c('test', 'test', 'tset', 'tisk - tisk'), 
        stuff=c('blah', 'blag', 'gah', 'nah') , 
        numbers=c(1,2,3, 4)) 
0123私に与えます
+0

'テスト%>%に変異(ラベル= GSUB( '_ [し^ _ ] * $ '、' '、label)) ' – alistaire

答えて

3

我々はsubを使用することができ、これは、任意の外部のパッケージなしで行うことができる

test$label <- sub("_[^_]+$", "", test$label) 
test$label 
#[1] "test_test" "test_tom" "tset_eat" "tisk - tisk" 
1

これも動作します:

gsub('(.*)_\\w+', '\\1', test$label) 
#[1] "test_test" "test_tom" "tset_eat" "tisk - tisk"