有没有办法删除不是全部数值的数据行?

问题描述 投票:1回答:2

我有两列数据。数据的每一列都有数字值,但其中一些没有任何数值。我想删除没有所有数值的行。实际上,数据有1000行,但为简化起见,我在这里将数据文件制作得较小。谢谢!

a <- c(1, 2, 3, 4, "--")
b <- c("--", 2, 3, "--", 5)
data <- data.frame(a, b) 
r numeric data-cleaning
2个回答
2
投票
data[!is.na(Reduce(`+`, lapply(data, as.numeric))), ] a b 2 2 2 3 3 3

并且要导入数据,请使用stringsAsFactors = FALSE

或使用sapply()

data[!is.na(rowSums(sapply(data, as.numeric))), ]


1
投票
library(dplyr) data %>% filter_all(all_vars(!is.na(as.numeric(.)))) # a b #1 2 2 #2 3 3

[如果我们不喜欢警告,则一个选项是通过检查从开始([0-9.]+)到结束(^)的一个或多个数字($)包括一个点来检测仅包含正则表达式的数字元素str_detect

的字符串
library(stringr)
data %>% 
    filter_all(all_vars(str_detect(., "^[0-9.]+$")))
#  a b
#1 2 2
#2 3 3

如果我们只有--作为非数字,则更容易删除
data[!rowSums(data == "--"),] # a b #2 2 2 #3 3 3

数据

data <- data.frame(a,b, stringsAsFactors = FALSE)
© www.soinside.com 2019 - 2024. All rights reserved.