2

考虑跟随向量资源和矩阵团队。向量 res 表示索引,我只需要提取那些索引号在向量 res 中且性别 =“F”的名称。

我需要在 R 中执行此操作,因为我是 R 的新手,无法解决此问题。

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"    
4

3 回答 3

7

如果您team是 amatrix或 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"

基本思想是获取“F”性别行的索引(使用which),然后使用集合操作intersect将其与您的res索引进行“与”。还有一些unionsetdiff体有时会很有用。

于 2012-04-13T00:01:40.077 回答
7

有很多方法可以做到这一点。

您可以先选择哪些行在res

team$names[res]

然后你可以选择哪些gender"F"

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

请注意,team$genders[res]挑选出与 中的行相对应的性别res,然后过滤以仅接受那些是女性的。


如果你喜欢,你可以反过来做:

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

team$genders=="F"是一个长度的逻辑向量nrow(team)TRUE只要性别是“F”,FALSE否则。

1:nrow(team)生成行号,如果1:nrow(team) %in% resTRUE号在res.

上面写着“&确保性别是“F”并且行号在res“。


您甚至可以执行which(team$genders=="F")返回女性行号向量的操作,然后执行以下操作:

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

其中,女性和女性中都存在的选择intersect行号。 res


而且我相信人们会想到更多的方法。

于 2012-04-13T00:04:55.860 回答
2
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"
于 2012-04-14T04:04:36.847 回答