Reputation: 1814
I am subsetting and ordering a dataframe according to an external vector which contains IDs non-matching the col name. How can I avoid the NAs in the final data.frame?
a<-c(2, 4, 6, 6, 8, 10, 12, 13, 14)
b<-c(21:29)
name<-c("O1", "O2", "O3", "O4", "O5","O6", "O7", "O8", "O9")
ID<-rep(c("no","bo", "fo"), each=3)
df<-data.frame(name,ID, a, b)
target<-c("O5","O6", "O7", "O3", "O4", "O1", "O2", "O10", "O11")
newdf <- df[match(target, df$name),]
name ID a b
5 O5 bo 8 25
6 O6 bo 10 26
7 O7 fo 12 27
3 O3 no 6 23
4 O4 bo 6 24
1 O1 no 2 21
2 O2 no 4 22
NA <NA> <NA> NA NA
NA.1 <NA> <NA> NA NA
Upvotes: 1
Views: 54
Reputation: 887501
We can use nomatch=0
in the match
. By default, the non matching elements will be occupied by 'NA'. When there is an NA
element, it will add an additional NA
row for each NA
from the match
.
df[match(target, df$name, nomatch=0),]
Or we can use %in%
to get the logical index of elements in 'name' that are also in target and use that as row index.
df[df$name %in% target,]
Upvotes: 1