首页 > 解决方案 > 如果 A 列中的因子与 B 列中的因子匹配,如何删除行

问题描述

我有一个包含 900 万行和 3 个变量的数据框。这 3 个变量是 Origin(因子 w/46 个级别)、Destination(因子 w/46 个级别)和吞吐量 (int)。

我的数据框的简化版本如下所示: https ://ibb.co/0p7g37B

我想删除 Origin 等于 Destination 的行(例如 12th = 12th 或 16th=16th)

我希望我的输出看起来像这样: https ://ibb.co/k6h7qc2

数据:

df <- structure(list(Origin = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L
  ), .Label = c("12th", "16th"), class = "factor"), Destination = structure(c(1L, 
  1L, 4L, 4L, 2L, 3L, 5L), .Label = c("12th", "16th", "CIVC", "COLS", 
  "FTVL"), class = "factor"), Throughput = c(1L, 2L, 1L, 4L, 2L, 
  1L, 7L)), class = "data.frame", row.names = c(NA, -7L))

标签: rdataframeintlevels

解决方案


Bruno"s 和 Nitesh"s 的答案都产生了所需的输出,但我认为不需要额外的 mutate 语句。您可以直接过滤结果:

df <- df %>% filter(Origin != Destination)

还有一件事:为了能够比较两个因子变量,它们应该具有相同的水平。您应该以它们都具有相同级别的方式编辑起点或终点变量的级别。


推荐阅读