[R] If find x, then y, else do nothing

Joshua Wiley jwiley.psych at gmail.com
Fri Aug 5 23:25:26 CEST 2011


Hi Edward,

You can try something like:

u.ppl <- unique(init.dat1$grid)
l.ppl <- ifelse(grepl(4, init.dat1$Slide1_RESP), 2,
                init.dat1$Slide1_RESP)

Note that this is not exact as you have not provided a reproducible
example.  I am not exactly sure how you are  putting 1 for 2 and 2 for
4, if the value is equal to 4, but presumably it is clearer with data.
 In any event, look at ?ifelse it is something like a vectorized if
statement and is, I believe, preferable to your use of a for loop.  I
can probably give you a runnable solution if you can give the first
few rows of the relevant data.

Cheers,

Josh

On Fri, Aug 5, 2011 at 2:15 PM, Edward Patzelt <patze003 at umn.edu> wrote:
> I want to write code that says "If you find an element equal to 4 in this
> vector for each person in the data set tested separately, then put in 1 for
> 2 and 2 for 4, else leave the variable as is"
>
>  u.ppl <- (unique(init.dat1$grid))
>      l.ppl <- length(u.ppl)
>        for (i in 1:l.ppl)
>        {
>          if (grep("4",init.dat1$Slide1_RESP)) {2 == 1, 4 == 2}; else
> init.dat1$Slide1_RESP
>
>        }
>
> --
> Edward H. Patzelt
> Research Assistant – TRiCAM Lab
> University of Minnesota – Psychology/Psychiatry
> VA Medical Center
> Office: S355 Elliot Hall - Twin Cities Campus
> Phone: 612-626-0072  Email: patze003 at umn.edu
>
> Please consider the environment before printing this email
> www.psych.umn.edu/research/tricam
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list