Quick way to check if elements in a list are numbers (but as.character())

Viewed 28

I have a list list_A, that I want to iterate through in a forloop. However, I want to iterate through only the elements that are number. Example below:

#generate exmaple: 
list_A <- list("A","B","C","8","1","5","3","U","2","C","6")
names(list_A) <- c("A","B","C","8","1","5","3","U","2","C","6")

# my attempt
for (i in names(list_A)) {
  if (i == ??) {
  print("is a number")
  }
}
1 Answers

We can use

 sapply(list_A, function(x) is.na(as.numeric(x)))

or with grep

sapply(list_A, function(x) !grepl('\\D', x))
  A     B     C     8     1     5     3     U     2     C     6 
FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE 

Or if the length is just 1 per list element, unlist and apply grepl or as.numeric at once

!grepl('\\D', unlist(list_A))
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE

Or in the for loop

for(l in list_A) {
     if(!grepl('\\D', l)) print(paste(l, ' is a number'))
}
[1] "8  is a number"
[1] "1  is a number"
[1] "5  is a number"
[1] "3  is a number"
[1] "2  is a number"
[1] "6  is a number"
Related