是否有 R 命令来确定数据帧值是否可以转换为数字格式?



R中有没有办法找出值是否可以转换为数字格式?我通常会type.convert(as.is=T)将我的列转换为数字并执行数学函数。但是我当前的表有一些无法转换的值。我想在以"a"结尾的列中提取那些不包含数字可转换字符的非 NA 行。

数据

df <- data.frame(names=c("Shawn", "James", "Caleb", "David"), a_a=c("1",NA,"bad","1"),a_b=c("1",NA,"1","good"))
names   a_a  a_b
1 Shawn   1    1
2 James <NA> <NA>
3 Caleb bad    1
4 David   1 good
df %>%
filter_at(vars(ends_with("a")), any_vars(!is.na(.) & class(.) != "character")

期望的输出

names   a_a  a_b
Caleb   bad    1

有几个选项,

1(转换为numeric,然后自动将非NA元素转换为我们可以捕获的NAis.na

library(dplyr)
df %>% 
type.convert(as.is = TRUE) %>%
filter_at(vars(ends_with('a')), any_vars(is.na(as.numeric(.)) & !is.na(.)))
#   names a_a a_b
#1 Caleb bad   1

在上面,当存在"字符"元素时,转换为numeric时会出现一条警告消息


2( 使用正则表达式检测器

library(dplyr)
library(stringr)
df %>% 
filter_at(vars(ends_with('a')), 
any_vars(str_detect(., '[A-Za-z]') &  class(.) != "character"))
#   names a_a a_b
#1 Caleb bad   1

可能在基本 R 中:

# drop the 'irrelevant' rows - ie the ones with NAs upfront
df2 <- df[!is.na(df[, grep("_a$", names(df))]), ]
# then identify the ones where as.numeric would result in NA
res <- df2[is.na(as.numeric(df2[, grep("_a$", names(df2))])), ]

结果:

names a_a a_b   
Caleb bad   1 

最新更新