# Re: [R] If Then Trouble

From: Joshua Wiley <jwiley.psych_at_gmail.com>
Date: Sun, 24 Apr 2011 13:18:55 -0700

Hi John,

On Sun, Apr 24, 2011 at 1:10 PM, Sparks, John James <jspark4_at_uic.edu> wrote:
> Dear R Helpers,
>
> I have another one of those problems involving a very simple step, but due
> to my inexperience I can't find a way to solve it.  I had a look at a
> number of on-line references, but they don't speak to this problem.
>
> I have a variable with 20 values
>
>> table (testY2\$redgroups)
>
>    1     2     3     4     5     6     7     8     9    10    11    12
> 13    14    15    16    17    18    19    20
>   69   734  6079 18578 13693  6412  3548  1646   659   323   129    88
> 90    40    57    33    36    17     6    13
>
> Values 18,19 and 20 have small counts.  So, I want to set the value of
> redgroups for these rows to 17 in order to combine groups.  I would think
> that it would be as easy as
>
> if(testY2\$redgroups>17) testY2\$redgroups<-17

"if" is not vectorized, it is designed for using in things like logic trees (e.g., if (na.rm) {remove-missing-values} else ....). You are looking for ifelse (see ?ifelse for documentation). Something like:

testY2\$redgroups <- with(testY2, ifelse(redgroups > 17, 17, redgroups))

HTH, Josh

>
> following the syntax that I have seen in the manuals.  However, I get the
> error message
>
> Warning message:
> In if (testY2\$redgroups > 17) testY2\$redgroups <- 17 :
>  the condition has length > 1 and only the first element will be used
>
> Can someone please tell me the correct syntax for this?  I would really
> appreciate it.
>
> Appreciatively yours,
> --John J. Sparks, Ph.D.
>
> ______________________________________________
> R-help_at_r-project.org mailing list
>
https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

```--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help