2014-09-11 70 views
3

如何刪除DF中具有字母的行,當它們應該是數字時?一個表的例子可能是:使用R去除字符串中的字符

DT = data.table(x=c("b","b","b","a","a"),v=rnorm(5), j=c("122","1223","g21bg","43","534")) 
DF=data.frame(DT) 

,我需要得到:

x   v  j 
b 0.4220836 122 
b -1.9492471 1223 
a 1.4615694 43 
a -0.2294917 534 

可以是任何字符的非數字。 我試圖

library(stringr) 
str_detect(DF$j, letters) 

,但我得到:

錯誤check_pattern(模式,字符串):字符串的長度和 模式不兼容

+0

一個可重複的例子會很棒。檢查此:http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Henk 2014-09-11 14:00:52

回答

5

使用grepl

DF[!grepl("[A-Za-z]", DF$j), ] 
## x   v j 
##1 b -1.3157423 122 
##2 b -1.3514456 1223 
##4 a 0.7508370 43 
##5 a 0.3476453 534 

但是,真的,你有一個data.table對象,爲什麼你將它轉換爲data.frame?這對我來說沒有任何意義。你可以在做同樣的你原來data.table

DT[!grepl("[A-Za-z]", j), ] 
# x   v j 
# 1: b 0.03008628 122 
# 2: b -0.72063192 1223 
# 3: a 0.94851720 43 
# 4: a -0.72384496 534 

或者使用grepinvert = TRUE

DT[grep("[A-Za-z]", j, invert = TRUE), ] 

合併或者,如果你想(在您的文章等)使用str_detect

library(stringr) 
DT[!str_detect(j, "[A-Za-z]"), ] 

雖然str_detect只是grepl的包裝