如果 A 列中的因子与 B 列中的因子匹配,如何删除行
How to remove rows if factor in column A matches factor in column B
我有一个包含 900 万行和 3 个变量的数据框。这 3 个变量是起点(46 级因子)、目的地(46 级因子)和吞吐量(整数)。
我的数据框的简化版本如下所示:
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))
您可以创建一个字符串值为 1 和 0 的虚拟变量。如果原始值和目标值相同,则为 1,否则为 0。然后,您可以过滤掉新创建的虚拟变量中字符串值为 0 的行 variable.do 如下所示:
data = read.csv("filepath of csv file.csv")
data$newdummy = ifelse(data$Origin == data$Destination, '1' ,'0')
data1 <- data[data$newdummy == '0',]
稍后,您可以删除创建虚拟值的列 -
data1 <- data1[-4]
如果新的虚拟列的位置是第 3。
希望对您有所帮助。
您可以使用 tidyverse。
library(tidyverse)
df <- tribble(~Origin,~Destination,~Throughput,
"12th","12th",1,
"12th","12th",2,
"12th","COLS",1,
"12th","COLS",4,
"16th","16th",2,
"16th","CIVC",1,
"16th","FTVL",7)
df %>%
mutate(is_equal = if_else(Origin == Destination,
TRUE,
FALSE)) %>%
filter(is_equal == FALSE) %>%
select(-is_equal)
Bruno"s and Nitesh"的两个答案都会产生所需的输出,但我认为不需要额外的 mutate 语句。您可以直接筛选结果:
df <- df %>% filter(Origin != Destination)
还有一件事:为了能够比较两个因子变量,它们应该具有相同的水平。您应该以具有相同级别的方式编辑原始级别或目标变量。
我有一个包含 900 万行和 3 个变量的数据框。这 3 个变量是起点(46 级因子)、目的地(46 级因子)和吞吐量(整数)。
我的数据框的简化版本如下所示: 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))
您可以创建一个字符串值为 1 和 0 的虚拟变量。如果原始值和目标值相同,则为 1,否则为 0。然后,您可以过滤掉新创建的虚拟变量中字符串值为 0 的行 variable.do 如下所示:
data = read.csv("filepath of csv file.csv")
data$newdummy = ifelse(data$Origin == data$Destination, '1' ,'0')
data1 <- data[data$newdummy == '0',]
稍后,您可以删除创建虚拟值的列 -
data1 <- data1[-4]
如果新的虚拟列的位置是第 3。
希望对您有所帮助。
您可以使用 tidyverse。
library(tidyverse)
df <- tribble(~Origin,~Destination,~Throughput,
"12th","12th",1,
"12th","12th",2,
"12th","COLS",1,
"12th","COLS",4,
"16th","16th",2,
"16th","CIVC",1,
"16th","FTVL",7)
df %>%
mutate(is_equal = if_else(Origin == Destination,
TRUE,
FALSE)) %>%
filter(is_equal == FALSE) %>%
select(-is_equal)
Bruno"s and Nitesh"的两个答案都会产生所需的输出,但我认为不需要额外的 mutate 语句。您可以直接筛选结果:
df <- df %>% filter(Origin != Destination)
还有一件事:为了能够比较两个因子变量,它们应该具有相同的水平。您应该以具有相同级别的方式编辑原始级别或目标变量。