在R中提取相应的值

时间:2019-08-08 17:25:56

标签: r

我试图在su19$q2中找到标记为“是”的行,并从那里在su19$q1中找到其对应的值(学校名称)。但是,我尝试的所有操作似乎均不起作用。

su19$q1[su19$q2 == "Yes"]

我不明白为什么这不起作用。

我的期望是,对于q2中的每个“是”响应,将从q1列中返回其相应学校的列表。

2 个答案:

答案 0 :(得分:1)

这应该有效:

su19$q1[which(su19$q2 == "Yes")]

where()函数返回给定矢量为“ True”的索引。在您的示例中,表达式su19 $ q2 ==“ Yes”返回一个等于True或False的向量,具体取决于等式是否成立(请参见https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/which

答案 1 :(得分:0)

我正在创建一个新答案,因为注释中无法添加代码

su19 <- data.frame(q1 = c("Santiago Canyon College","College of 
       Alameda","Cerritos College","Cuyamaca college","Cypress College","Folsom Lake 
       College"), q2= c("Yes","Yes","Yes","Yes","Yes","Yes"),stringAsFactors= FALSE)

                        q1  q2
 1 Santiago Canyon College Yes
 2      College of Alameda Yes
 3        Cerritos College Yes
 4        Cuyamaca college Yes
 5         Cypress College Yes
 6     Folsom Lake College Yes

@ Chelmy88解决方案

su19$q1[which(su19$q2 == "Yes")]
[1] "Santiago Canyon College" "College of Alameda"      "Cerritos College"        "Cuyamaca college"        "Cypress College"        
[6] "Folsom Lake College" 

我的解决方案

su19[which(su19$q2 == "Yes"),]$q1
[1] "Santiago Canyon College" "College of Alameda"      "Cerritos College"        "Cuyamaca college"        "Cypress College"        
[6] "Folsom Lake College" 

如果您没有data.frame,但只有矢量

q1 <- c("Santiago Canyon College","College of Alameda","Cerritos College","Cuyamaca college","Cypress College","Folsom Lake College")
q2 <- c("Yes","Yes","Yes","Yes","Yes","Yes")

su19$q1[which(su19$q2 == "Yes")]
[1] "Santiago Canyon College" "College of Alameda"      "Cerritos College"        "Cuyamaca college"        "Cypress College"        
[6] "Folsom Lake College"