[R] trouble with ifelse statement

Rui Barradas ruipbarradas at sapo.pt
Wed May 16 23:48:12 CEST 2012


Hello,

'sample' is a really bad name for a variable, it's already taken, it's an R
function.

sample>1 && sample<5  # '&&' is not vectorized, it's '&' you want.

# Without 'ifelse'
raw.saliva.data$max.cort[index] <-  raw.saliva.data$cortisol[index & sample
> 1 & sample < 5]

Negate this last conjunction if you want to set the other 'max.cort' to NA,

!(index & sample > 1 & sample < 5)

And, finally, this is untested. Give a small dataset example, including
'sample' (after calling it something else).

Hope this helps,

Rui Barradas

la mer wrote
> 
> Hello,
> 
> I apologize in advance for not providing sample data, I'm a very new to R
> and can't easily generate appropriate sample data quickly. I'm hoping
> someone can offer advice without it.
> 
> This code below works and does what I want it to do, which is for a given
> row in my dataframe, where the variable "peak.cort" = max, it makes the
> value of another variable "max.cort" = to match the value of a third
> variable "cortisol" for that row.
> 
> *************
> index <- raw.saliva.data$peak.cort == 'max'
>             raw.saliva.data$max.cort[index] <-
> (raw.saliva.data$cortisol[index])
> *************
> 
> Now, I want to execute this function only if the value of a fourth
> variable, "sample" is >1 and <5. I tried to add an ifelse statement to the
> code above so that it looks like this:
> 
> *************
> index <- raw.saliva.data$peak.cort == 'max'
>             raw.saliva.data$max.cort[index] <- ifelse(sample>1 &&
> sample<5,
> raw.saliva.data$cortisol[index], NA)
> *************
> 
> and I get this error: Error in sample > 1 :
>   comparison (6) is possible only for atomic and list types
> 
> I can't figure out how to fix this problem. Any advice is appreciated.
> 
> Thank you.
> -- 
> *Melissa*
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help@ 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.
> 


--
View this message in context: http://r.789695.n4.nabble.com/trouble-with-ifelse-statement-tp4630309p4630316.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list