Subsetting matrices

前端 未结 3 1553
遇见更好的自我
遇见更好的自我 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:28

    This should work if your team is either a matrix or a data.frame:

    # emulate your data
    team <- data.frame(names=LETTERS, genders=rep(c("M","F"), 13))
    res <- 10:26
    
    team[intersect(res, which(team[,"genders"]=="F")), "names"]
    #[1] J L N P R T V X Z
    #Levels: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
    
    # Try with a matrix instead of data.frame
    team <- as.matrix(team)
    team[intersect(res, which(team[,"genders"]=="F")), "names"]
    #[1] "J" "L" "N" "P" "R" "T" "V" "X" "Z"
    

    The basic idea is to get the indices of the "F" gender rows (using which) and then use the set operation intersect to AND it with your res indices. There are also union and setdiff variants that can be useful at times.

    0 讨论(0)
  • 2021-01-07 05:35
    team <- structure(c("aa", "ab", "al", "alp", "amr", "and", "an", "anv", 
    "as", "ed", "neh", "pan", "poo", "ra", "roh", "shr", "sub", "val", 
    "xi", "M", "M", "M", "M", "F", "M", "M", "F", "M", "M", "F", 
    "M", "F", "M", "M", "F", "M", "M", "M"), .Dim = c(19L, 2L), .Dimnames = list(
        NULL, c("names", "genders")))
    
     team[,"names"][ intersect(  which(team[,"genders"]=="F") , res ) ]
    #[1] "amr" "shr"
     team[,"names"][ team[,"genders"]=="F" & 1:NROW(team) %in% res  ]
    #[1] "amr" "shr"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题