Considering following vector res and matrix team.
the vector res represent indices, and I require to extract only those names whose index number is in vector res and gender=”F”.
I need to do this in R and as I am a newbie to R, could not resolve this.
res
[1] 2 12 16 5 6 19 17 14 9 4
team
names genders
[1,] "aa" "M"
[2,] "ab" "M"
[3,] "al" "M"
[4,] "alp" "M"
[5,] "amr" "F"
[6,] "and" "M"
[7,] "an" "M"
[8,] "anv" "F"
[9,] "as" "M"
[10,] "ed" "M"
[11,] "neh" "F"
[12,] "pan" "M"
[13,] "poo" "F"
[14,] "ra" "M"
[15,] "roh" "M"
[16,] "shr" "F"
[17,] "sub" "M"
[18,] "val" "M"
[19,] "xi" "M"
There are many ways to do this.
You could first pick which rows are in
res:Then you can pick which ones have
genderbeing"F":Note that
team$genders[res]picks out the genders corresponding to the rows inres, and then you filter to only accept those that are female.If you liked, you could do it the other way round:
Here
team$genders=="F"is a logical vector of lengthnrow(team), beingTRUEwhenever the gender is “F” andFALSEotherwise.The
1:nrow(team)generates row numbers, and1:nrow(team) %in% resisTRUEif the row number is inres.The
&says “make sure that the gender is “F” AND the row number is inres“.You could even do
which(team$genders=="F")which returns a vector of row numbers for females, and then do:where the
intersectpicks row numbers that are present in bothresand the females.And I’m sure people with think of more ways.