Delete rows with negative values

In R, I am trying to delete rows in a dataframe (ants) that have a negative value under the heading of the "Turbidity" column. I tried

ants<-ants[ants$Turbidity<0,]

but it returns the following error:

Warning message:
In Ops.factor(ants$Turbidity, 0) : < not meaningful for factors

Any ideas why this could be? Perhaps I need to make negative NA values ​​before I delete all the NSs?

Any ideas are greatly appreciated, thanks!

@Joris: result

str(ants$Turbidity)

num [1: 291] 0 0 -0.1 -0.2 -0.2 -0.5 0.1 -0.4 0 -0.2 ...

+3
source share
4 answers

Marek is right, this is a data problem. Now be careful if you use [as.numeric (ants $ Turbidity], as it will always be positive. It gives factor levels (1 to length (ant turbidity)) rather than numerical factors.

:

tt <- as.numeric(as.character(ants$Turbidity))
which(!is.na(tt))

, . .

:

> Turbidity <- factor(c(1,2,3,4,5,6,7,8,9,0,"a"))
> tt <- as.numeric(as.character(Turbidity))
Warning message:
NAs introduced by coercion 
> which(is.na(tt))
[1] 11

as.numeric(as.character(...)) , NA, . :

> Turbidity[tt > 5]
[1] 6    7    8    9    <NA>
Levels: 0 1 2 3 4 5 6 7 8 9 a
+3

summary(ants) , , .

. .

+3

. as.character (. ).


, ants$Turbidit factor. ,

ants <- ants[as.numeric(as.character(ants$Turbidity)) > 0,]

ants <- subset(ants, as.character(as.numeric(Turbidity)) > 0)

But the real problem is that your data is not ready for analysis. Such a conversion must be done at the beginning. You have to be careful, as there may be non-numeric values.

0
source

This should also work using Tidyverse (assuming the column is the correct data type).

ants %>% dplyr::filter(Turbidity >= 0)
0
source

Source: https://habr.com/ru/post/1775611/