Subsetting matrices

前端 未结 3 1587
遇见更好的自我
遇见更好的自我 2021-01-07 05:01

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=

3条回答
  •  被撕碎了的回忆
    2021-01-07 05:49

    There are many ways to do this.

    You could first pick which rows are in res:

    team$names[res]
    

    Then you can pick which ones have gender being "F":

    team$names[res][  team$genders[res]=="F"   ]
    

    Note that team$genders[res] picks out the genders corresponding to the rows in res, and then you filter to only accept those that are female.


    If you liked, you could do it the other way round:

    team$names[  team$genders=="F" & (1:nrow(team) %in% res) ] 
    

    Here team$genders=="F" is a logical vector of length nrow(team), being TRUE whenever the gender is "F" and FALSE otherwise.

    The 1:nrow(team) generates row numbers, and 1:nrow(team) %in% res is TRUE if the row number is in res.

    The & says "make sure that the gender is "F" AND the row number is in res".


    You could even do which(team$genders=="F") which returns a vector of row numbers for females, and then do:

    team$names[ intersect(  which(team$genders=="F") , res ) ]
    

    where the intersect picks row numbers that are present in both res and the females.


    And I'm sure people with think of more ways.

提交回复
热议问题