r - 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")
解决方案
如果它是一个数字列,那么这些方法应该可以工作。如果有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))
推荐阅读
- c# - 在与 EF Core 一起使用之前更改单个字段值
- php - 将自定义字段插入自定义帖子类型
- reactjs - CRA:将特别大的模块提取到单独的块中?
- php - 在 bitmex API 中更改 SYMBOL CONST
- sql - 使用 JSON1 跨多个表聚合 SQLite 查询
- node.js - 错误 TS2322:类型“任何”不可分配给类型“从不”
- python - 插入表并得到错误: sqlite3.ProgrammingError: You did not provide a value for binding 1
- python - Tkinter - 要求用户输入整数,直到他们在 tkinter 输入框中给出有效响应
- vue.js - 如何解决已分配计算属性但在 vue api 组合中没有设置器的问题?
- codenameone - Codenameone: start() 方法并不总是在应用程序恢复时调用