首页 > 解决方案 > R:删除所有满足特定条件的行

问题描述

我正在尝试清理一个dataframe. 我创建了一个指标变量,它是 1、0 或 -1。例如:

Name   Indicator_1
A      1
B      0
C      1
D     -1

现在我试图删除所有> 0的行,给我一个dataframe这样的:

 Name   Indicator_1
    B      0
    D     -1

到目前为止,我已经尝试了几种不同的方法,包括:

df <- df[df$Indicator_1 > 0,]
df <- df(df, select = -c(Indicator_1 >0))
df <- df %>% slice(-c(Indicator_1 >0))
df <-df[!(df$Indicator_1 >0),]

不幸的是,这些方法都没有按预期工作。要么所有条目都变成NA,要么什么都没有发生。

我看错了吗?我会很感激任何帮助,并且没有包裹偏好。

编辑:一些Indicator_1条目是NA他们自己的。

编辑:添加了重复

structure(list(Name = c("K", "L", "Y", 
"S", "R", "W"),Indicator_1 = c(NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_)), row.names = c(NA, 
6L), class = "data.frame")

标签: r

解决方案


如果它是一个数字列,那么这些方法应该可以工作。如果有NA元素,创建一个逻辑条件is.na

subset(df, Indicator_1 >0 & !is.na(Indicator_1))
#   Name Indicator_1
#1    A           1
#3    C           1

如果它不是numeric类并且它没有任何字符串,我们可以使用type.convert更改class

subset(type.convert(df, as.is = TRUE), Indicator_1 >0 & !is.na(Indicator_1))

 

数据

df <- structure(list(Name = c("A", "B", "C", "D"), Indicator_1 = c(1L, 
0L, 1L, -1L)), class = "data.frame", row.names = c(NA, -4L))

推荐阅读