[R] Two conditions selection

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Wed Aug 5 01:58:30 CEST 2015


You need to read up on indexing in R.  What you want is logical indexing.  You can use just the vectors you created (since you didn't save the data frame that you created) like this

> cycle=c(rep(1,3),rep(2,3),rep(3,3),rep(4,3))
> col=c(rep("blue",2),rep("green",2),rep("blue",2),rep("green",2),rep("blue",2),rep("green",2))
> values=c(1:12)
> values[col==blue & cycle==1]

Or save the data frame and return the rows that you want like this

> df <- data.frame(cycle,col,values)
> df[df$col==blue & df$cycle==1, ]

Hope this is helpful,

Dan

Daniel Nordlund, PhD
Research and Data Analysis Division
Services & Enterprise Support Administration
Washington State Department of Social and Health Services


-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Rodrigo Díaz
Sent: Tuesday, August 04, 2015 1:50 PM
To: r-help at r-project.org
Subject: [R] Two conditions selection

Hi. I have a matrix like this: 
cycle=c(rep(1,3),rep(2,3),rep(3,3),rep(4,3))col=c(rep("blue",2),rep("green",2),rep("blue",2),rep("green",2),rep("blue",2),rep("green",2))values=c(1:12)data.frame(cycle,col,values)
#  cycle   col values#1      1  blue      1#2      1  blue      2#3      1 green      3#4      2 green      4#5      2  blue      5#6      2  blue      6#7      3 green      7#8      3 green      8#9      3  blue      9#10     4  blue     10#11     4 green     11#12     4 green     12
I want to select or extract values matching 2 conditions. For example: values from col "blue" and cycle "1". If I use : values[col==blue] I get all blue values. I tried using values[c(col==blue,cycle==1)] but is not working. Please help. I have a very big data matrix and I do not wanna go to excel and start cutting the data. Thanks. 

 		 	   		  
	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list