Subsetting matrices

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

提交回复
热议问题