2014-09-11 2 views
3

Comment puis-je supprimer des lignes dans un DF contenant des lettres alors qu'elles sont supposées être des nombres? Un exemple de table pourrait être:Suppression de caractères dans une chaîne avec 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) 

Et je dois obtenir:

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

Peut-être un caractère non numérique. J'ai essayé

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

Mais je reçois:

Erreur dans check_pattern (motif, chaîne): Longueurs de chaîne et modèle non compatible

+0

Un exemple reproductible serait génial. Vérifiez ceci: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Henk

Répondre

5

Utilisez 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 

Mais, vraiment, vous avoir un objet data.table, pourquoi le convertis-tu en data.frame ?? Cela n'a aucun sens pour moi. Vous pouvez faire de même dans votre original 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 

Ou en utilisant grep combiné avec invert = TRUE

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

Ou si vous voulez utiliser str_detect (comme dans votre post)

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

Bien que str_detect est juste un emballage pour grepl

Questions connexes