按列过滤数据集中的行 [英] Filtering rows in a dataset by columns
问题描述
我有下表:
FN LN LN1 LN2 LN3 LN4 LN5
abbxxxx
acbde NA NA
adcabxx
aebcdxe
我正在过滤LN1中存在LN的记录LN5。
我使用的代码:
testFilter = filter(测试,LN%in%c(LN1,LN2,LN3,LN4,LN5))
结果不是我所期望的:
ï..FNLN LN1 LN2 LN3 LN4 LN5
1 abbxxxx
2 aclt< NA> < NA>
3 adcabxx
4 aebcdxe
我知道 c(LN1,LN2,LN3,LN4,LN5)
给出: b b c b x d a c x e b d x NA x x x NA x e
并且知道这是错误所在。 / p>
理想情况下,我只想返回第一条和第四条记录。
FN LN LN1 LN2 LN3 LN4 LN5
abbxxxx
aebcdxe
我只想使用列名来过滤它们。这只是540万条记录的一部分。
使用 apply :
#data
df1<-read.table(text =
FN LN LN1 LN2 LN3 LN4 LN5
abbxxxx
acbde NA NA
adcabxx
aebcdxe,标头= TRUE,stringsAsFactors = FALSE)
df1 [apply(df1,1,function(i)i [2]%in%i [3: 7]),]
#FN LN LN1 LN2 LN3 LN4 LN5
#1 abbxxxx
#4 aebcdxe
注意:考虑针对大型数据集使用以下其他解决方案,该解决方案可以为 60 倍于此 apply 解决方案。
I have the following table:
FN LN LN1 LN2 LN3 LN4 LN5
a b b x x x x
a c b d e NA NA
a d c a b x x
a e b c d x e
I'm filtering records for which LN is present in LN1 to LN5.
The code I used:
testFilter = filter(test, LN %in% c(LN1, LN2, LN3, LN4, LN5))
The result is not what I expect:
ï..FN LN LN1 LN2 LN3 LN4 LN5
1 a b b x x x x
2 a c b d e <NA> <NA>
3 a d c a b x x
4 a e b c d x e
I understand that c(LN1, LN2, LN3, LN4, LN5)
gives: "b" "b" "c" "b" "x" "d" "a" "c" "x" "e" "b" "d" "x" NA "x" "x" "x" NA "x" "e"
and know this is where the mistake is.
Ideally, I want to return only the 1st and 4th record.
FN LN LN1 LN2 LN3 LN4 LN5
a b b x x x x
a e b c d x e
I want to filter them only using column names. This is just a subset of 5.4M records.
Using apply:
# data
df1 <- read.table(text = "
FN LN LN1 LN2 LN3 LN4 LN5
a b b x x x x
a c b d e NA NA
a d c a b x x
a e b c d x e", header = TRUE, stringsAsFactors = FALSE)
df1[ apply(df1, 1, function(i) i[2] %in% i[3:7]), ]
# FN LN LN1 LN2 LN3 LN4 LN5
# 1 a b b x x x x
# 4 a e b c d x e
Note: Consider using other solutions below for big datasets, which can be 60 times faster than this apply solution.
这篇关于按列过滤数据集中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!