【问题标题】:Is there an R command to find out if dataframe values can be converted into numeric format?是否有 R 命令来确定数据帧值是否可以转换为数字格式?
【发布时间】:2020-05-10 05:51:18
【问题描述】:

在 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

【问题讨论】:

  • 你需要df %&gt;% type.convert(as.is = TRUE) %&gt;% filter_at(vars(ends_with('a')), any_vars(is.na(as.numeric(.))))
  • @akrun OP 仅使用列a_a(第二列无关),并且第三行是唯一通过数字转换引入新NA的行;
  • @Gregor - 恢复 Monica 我有更多的列和行。以“图表”结尾的 12000 行和 4 列。应该制作更好的样品。
  • 是的,当然你有更多的数据。我认为令人困惑的是您在a_b 第 4 行中有“好”,“好”不能转换为数字,但它不会出现在您的预期输出中。很容易错过您显示 2 列但仅测试 1 列。

标签: r dataframe filter dplyr


【解决方案1】:

有几个选项,

1) 转换为numeric,然后自动将非NA元素转换为NA,我们可以使用is.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

【讨论】:

  • 请注意,正则表达式 '\\D' 仅适用于正整数。
【解决方案2】:

可能在基础 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 

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2019-12-24
    • 2020-04-22
    • 2021-08-26
    相关资源
    最近更新 更多