Skip to content

If condition using accessors

5 messages · Peter Ehlers, David Winsemius, Vitória Magalhães Piai

#
Hi,

I'm quite new using R and have got no one to help me get through it. 
Hopefully someone can help me with one problem I've been struggling with 
for the last hours!!
(Sorry if I'm using the wrong terminology as well!)

I have a data matrix in which SIE is one of my variables. What I need to 
do now is to create a new variable (group) if a certain condition in SIE 
is met.
I tried:

if (data2$SIE < 50.646){
data2$group=as.factor("small")
}
which gives me "In if (data2$SIE < 50.646) { :  the condition has length 
 > 1 and only the first element will be used"

and
ifelse (data2$SIE < 50.64593, data2$group = 
as.factor("small"),data2$group = as.factor("large"))
with "Error: unexpected '=' in "ifelse (data2$SIE < 50.64593, data2$group ="

I tried all other kinds of variations and so far, nothing!!

Is there a good way to do this that someone could teach me?
Thank you so much,
Vit?ria
#
Vit?ria Magalh?es Piai wrote:
Do all of the following:

?"="
?"=="
?"if"
?ifelse

  -Peter Ehlers
#
Peter Ehlers wrote:
Actually, I assumed without checking that ?ifelse would
have an example of assignment of the result of the test.
(Maybe it could be added.)

yourVariable <- ifelse(...)

  -Peter Ehlers
#
On Nov 27, 2009, at 5:34 AM, Vit?ria Magalh?es Piai wrote:

            
If ( cond) is not vectorised. Ifelse is.
Almost... try:

data2$group <- ifelse (data2$SIE < 50.64593,  as.factor("small"),  
as.factor("large") )

... but that looks wrong to my wetware R interpreter, too, so could  
also try:

data2$group <- factor( ifelse (data2$SIE < 50.64593,  "small", "large" )

(And of course this would have been tested had you supplied a small  
test dataset, but this week I am being passive aggressive toward  
persons who don't follow the Posting Guide.)
#
Thanx.
I'll just post in here the way I solved it in case someone happens to 
need something similar in the future. It may not be the most elegant 
way, but it worked!

yes = "small"
no = "large"
data3$group = ifelse(data3$SIE < 50.64593,yes,no)
Peter Ehlers wrote: