[R] trouble with ifelse statement
R. Michael Weylandt
michael.weylandt at gmail.com
Wed May 16 23:51:11 CEST 2012
It seems like your problem is that R can't find your variable "sample"
and is instead finding its own sample() function which can't be
compared to an integer and is giving your problem.
It seems likely that sample is part of raw.saliva.data? If that's the
case, change sample --> raw.saliva.data$sample
However, I'm thinking that this isn't going to do quite what you
really want because sample is long (corresponding to all the rows, not
just the subset by index) -- you could probably do something like this
instead:
raw.saliva.data <- within(raw.saliva.data, max.cort[index] <- ifelse(
(sample > 1 && sample < 5)[index], cortisol[index], NA))
Since you're telling R to look within() raw.saliva.data, lookup should
probably work for you.
Note that we have to restrict both the (sample) and (cortisol) parts
of ifelse() to just the rows "index" for this to work (else things get
lined up wrong)
Note finally that you also have to reassign back to raw.saliva.data
for this to have an effect.
Hope this helps,
Michael
On Wed, May 16, 2012 at 5:01 PM, Melissa Rosenkranz
<melissarosenkranz at gmail.com> 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 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.
More information about the R-help
mailing list