简体   繁体   English

在R中提取相应的值

[英]Extracting corresponding Values in R

I am trying to find rows in su19$q2 marked "Yes", and from there find its corresponding value (names of schools) in su19$q1 . 我试图在su19$q2找到标记为“是”的行,然后在su19$q1找到其对应的值(学校名称)。 However, everything I am trying seems to not work. 但是,我尝试的所有操作似乎均不起作用。

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

I do not understand why this is not working. 我不明白为什么这行不通。

My expectation is that for every "Yes" response in q2, a list is returned of its corresponding school from column q1. 我的期望是,对于q2中的每个“是”响应,都会从q1列中返回其相应学校的列表。

This should work: 这应该工作:

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

The which() function returns the indices where the given vector is "True". which()函数返回给定矢量为“ True”的索引。 In your example the expression su19$q2 == "Yes" returns a vector of either True of False depending if the equality holds or not (see https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/which ) 在您的示例中,表达式su19 $ q2 ==“ Yes”返回一个等于True或False的向量,具体取决于相等性是否成立(请参阅https://www.rdocumentation.org/packages/base/versions/3.6.1/主题/其中

I am creating a new answer as adding code is not possible in comments 我正在创建一个新答案,因为注释中无法添加代码

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 solution @ Chelmy88解决方案

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

my solution 我的解决方案

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

If you don't have a data.frame , but vectors only 如果没有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" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM