考虑以下矢量res和矩阵团队。 vector res代表索引,我只需要提取索引号在vector res和gender =“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"
答案 0 :(得分:7)
如果您的team
是matrix
或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
将AND与您的res
索引一起使用。还有union
和setdiff
变体可能有用。
答案 1 :(得分: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)
的逻辑向量,只要性别为“F”为TRUE
,否则为FALSE
。
如果行号在1:nrow(team)
,则1:nrow(team) %in% res
生成行号,TRUE
为res
。
&
说“确保性别为”F“且行号位于res
”。
您甚至可以which(team$genders=="F")
返回女性行号的向量,然后执行:
team$names[ intersect( which(team$genders=="F") , res ) ]
intersect
选择 res
和女性中的行号。
我相信人们会想到更多的方法。
答案 2 :(得分: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"