r语言 - 快速检查列表中的元素是否为数字(但作为.character())的方法



我有一个列表list_A,我想在一个forloop中迭代。但是,我只想迭代数字元素。在下面的例子:

#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")
}
}

我们可以使用

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

或与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 

或者如果lengthlist元素仅为1,则unlist并立即应用greplas.numeric

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

或者在for循环

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"

相关内容

最新更新