[R] Conditional expressions in commands -- basic

Richard Sherman rss.pdx at gmail.com
Sun Mar 23 07:55:37 CET 2014


Sarah,

i = 1
while i  >  0 {
  print("Thank you")
  i = i + 1
}

---
Richard Sherman



> On Mar 22, 2014, at 8:06 PM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
> 
> Hi Richard,
> 
> ?if
> ?ifelse
> ?subset
> ?[
> 
> depending on the specific operation. See inline.
> 
> Given a data frame tdf with x, y, and a (or with vectors creating a
> data frame using):
> tdf <- data.frame(x=x, y=y, a=a)
> 
>> On Sat, Mar 22, 2014 at 10:21 PM, Richard Sherman <rss.pdx at gmail.com> wrote:
>> Hi all,
>> 
>> A simple question, new-ish to R, coming from Stata, and I yes I've looked at great length and not found ...
>> 
>> In Stata I might write (with * in place of #)
>> 
>> # regress y on x in the set of observations where a==1
>> reg y x if a==1
> 
> lm(y ~ x, data=subset(tdf, a==1))
> 
>> 
>> # descriptives on x where a==1
>> su x if a==1
> 
> summary(subset(tdf, a==1)$x)
> or
> summary(tdf[tdf$a == 1,])
> or if they are vectors
> summary(x[a==1])
> 
>> 
>> # generate a logical depending on the value of a variable
>> gen z = (a == 1)
> 
> z <- a==1
> 
>> 
>> # or likewise for a numeric
>> gen x = y if a == 1
> 
> I'm not sure what this one is supposed to do. What's x if a isn't 1?
> 
> But those examples should be enough to get you started, especially if
> you also read the Intro to R that comes with your R installation.
> Subsetting is a very basic operation, as you say, and pretty much
> every intro/tutorial I've read talks about it. I'm not sure where you
> looked in your extensive searching.
> 
> Sarah
> 
>> 
>> # show the values of a variable based on the value of another variable
>> di y if a ~= .
>> 
>> # generate a logical based on missing-ness of a variable
>> gen w = (a~=.)
>> 
>> or any of many similar operations conditional on the value of a variable.
>> 
>> Believe it or not this is a big obstacle to learning R.
>> 
>> ---
>> Richard Sherman
> 
> 
> -- 
> Sarah Goslee
> http://www.functionaldiversity.org




More information about the R-help mailing list