我是R的新手,并且编写了以下代码。但是,我相信可能会有更好的方法来实现以下代码:
在代码中,我多次复制并粘贴了一个代码,以从同一变量中滤除不同的观察结果。我尝试使用%notin%,但它似乎对我不起作用
select.other <- have_data[which(have_data$TOP_NM == 'Other'),names(have_data) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other <- select.other[which(select.other$SERIES_NM != 'Constant=1 in Q1'),names(select.other) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other <- select.other[which(select.other$SERIES_NM != 'Constant=1 in Q2'),names(select.other) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other <- select.other[which(select.other$SERIES_NM != 'Constant=1 in Q3'),names(select.other) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other <- select.other[which(select.other$SERIES_NM != 'Constant=1 in Q4'),names(select.other) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other <- select.other[which(select.other$SERIES_NM != 'Time: Quarterly'),names(select.other) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other <- select.other[which(select.other$SERIES_NM != 'Time: Quarterly Projected'),names(select.other) %in% c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")]
select.other
希望有一种更简单的方法可以给我相同的结果。在此先感谢您的帮助和指导
答案 0 :(得分:6)
在第一个过滤器之后,我们可以创建元素向量('v1')以创建逻辑向量(%in%
),然后取反(!
)来对不包含行的行进行子集化在“ TOP_NM”列中包含这些元素
v1 <- c('Constant=1 in Q1', 'Constant=1 in Q2', 'Constant=1 in Q3',
'Constant=1 in Q4', 'Time: Quarterly', 'Time: Quarterly Projected')
i1 <- !select.other$TOP_NM %in% v1
colsOfInterest <- c("TOP_NM","SERIES_NM","SERIES_VAL","RANK")
select.other[i1, colsOfInterest, drop = FALSE]
注意-这里我们假设'colssOfInterest'中的所有元素都与数据的列名匹配。如果不是,则使用intersect(names(select.other), colsOfInterest)
或将OP的代码与%in%