Anthony
Anthony

Reputation: 169

Removing elements containing any alphabetical characters from list in R

I have the list with the following elements:

c("1",  "2", "3", "abc",  "1as")

How would I be able to remove elements that contains alphabets from the list? For instance, for the example above, I would wish to get ("1" "2" "3") as the final list, but 1,2,3 are all string variables in this case.

Upvotes: 0

Views: 345

Answers (3)

TJ83
TJ83

Reputation: 71

A little longer, but you don't need to use grep to solve the problem. You could simply convert, and those that are converted (not NA) are the ones you want to keep:

test<-c("1","2","3","abc","1as")
test_num<-as.numeric(test)
test_num_clean<-test_num[!is.na(test_num)]

And if you prefer strings:

test_str<-as.character(test_num_clean)

Upvotes: 1

stevec
stevec

Reputation: 52578

Here's how

a <- c("1",  "2", "3", "abc",  "1as")
a[!grepl("[[:alpha:]]", a)]
# [1] "1" "2" "3"

Upvotes: 2

Chase
Chase

Reputation: 69211

Here's one solution using grep to identify the entries with [:alpha:] entries and negating them:

x <- c("1",  "2", "3", "abc", "1as")

x[-grep("[:alpha:]", x)]
#> [1] "1" "2" "3"

Created on 2019-02-08 by the reprex package (v0.2.1)

Upvotes: 1

Related Questions