从包含符号的连续数据中删除 data.frame 行

Remove rows from data.frame from continuous data containing symbols

我有一个 data.frame 列,该列应该有连续数据。但是,某些行的值带有“~”和“<”符号。

c.a <- c(1,5,3,7,4,9,2,3,7)
c.b <- c("a", "c", "f", "s", "r", "q", "w", "e", "t")
c.d <- c(1,4,6, '<5', '~34', 65, 45, 2, 6)
x <- data.frame(c.a, c.b, c.d)

objective 将删除 data.frame x

中的第 4 行和第 5 行

希望这不是一个重复的问题,但我进行了快速搜索但找不到解决方案。提前致谢。

您可以尝试转换为数字并丢弃那些非数字的

x[!is.na(as.numeric(as.character(x$c.d))),]

输出:

  c.a c.b c.d
1   1   a   1
2   5   c   4
3   3   f   6
6   9   q  65
7   2   w  45
8   3   e   2
9   7   t   6

您可以使用grepl()过滤:

x[grepl(x=as.numeric(x$c.d),"[^\d]"), ]

输出:

  c.a c.b c.d
1   1   a   1
2   5   c   4
3   3   f   6
4   9   q  65
5   2   w  45
6   3   e   2
7   7   t   6

我认为,如果你没有关闭 stringsAsFactors = F,你可能得不到想要的结果,你可以在创建数据框时这样做:

x <- data.frame(c.a, c.b, c.d, stringsAsFactors=F)
x$c.d <- as.numeric(x$c.d)
x[complete.cases(x),]

你也可以在代码的顶部做options(stringsAsFactors=F),这在很多情况下都会对你有帮助(如果适合你可以选择使用)。

运行 以上应该会给你想要的输出。

您可以使用此解决方案(感谢@Onyambu):

na.omit(transform(x,c.d=as.numeric(c.d))) 

转换 the factor to a numeric (as.numeric(levels(x[, 'c.d']))[x[, 'c.d']]),然后将 NA 索引到数据框之外:

x <- x[!is.na(as.numeric(levels(x[, 'c.d']))[x[, 'c.d']]), ]

这会产生一条警告消息 (warnings ≠ errors),您可以忽略它(之所以给出这个是因为转换非数字字符会产生 NA,但这正是我们想要的在这里做)。

Warning message:
In `[.data.frame`(x, !is.na(as.numeric(levels(x[, "c.d"]))[x[, "c.d"]]),  :
  NAs introduced by coercion

这就是结果,正如您所要求的:

  c.a c.b c.d
1   1   a   1
2   5   c   4
3   3   f   6
6   9   q  65
7   2   w  45
8   3   e   2
9   7   t   6