Achal Neupane
Achal Neupane

Reputation: 5719

Filter something that is not number or specific letter from character vector

I have a character vector called:

myvec<- c("122","112","ghtt1","fff","223F","X","Y")

How can I filter and get only numbers, 'X' and 'Y' as in the

Expected output:

122,112,X,Y

Upvotes: 0

Views: 47

Answers (2)

zx8754
zx8754

Reputation: 56189

We could also define fixed lookup list, then match.

# messy chromosome names:
myvec <- c("1","12","ghtt1","fff","22","X","Y")

# result
myvec[ which(myvec %in% c(1:22,"X","Y")) ]
# [1] "1"  "12" "22" "X"  "Y" 

Upvotes: 2

akrun
akrun

Reputation: 887251

We can use grep

grep("^([0-9]+|X|Y)$", myvec, value=TRUE)
#[1] "122" "112" "X"   "Y"  

Upvotes: 4

Related Questions