1

this is my first time using a if-else statement in R. I have a column (in a data frame) named 'Performance' that has percentages (some of which are estimates). I have created a new column named 'Estimate' which takes the last character of the 'Performance' column. Now, I want to make a column with the following conditions: If 'Estimate' = '*' then 'Estimate' = 'YES' else 'Estimate' = 'NO'. I just want to keep the new column name 'Estimate'. The statement I have written works, but I am getting an error message that says:

"Warning message: In if (data.set$Estimate == "*") { : the condition has length > 1 and only the first element will be used"

Here is my statement:

data.set$Estimate <- if (data.set$Estimate == '*') {data.set$Estimate = 'YES'} else{data.set$Estimate = 'NO'}

Can someone please explain why I am getting this error message, and/or what I would need to change to not get it? Any help is much appreciated.

1
  • Did you search for this error on SO? There are hundreds of answers to this already. Commented Sep 23, 2014 at 16:01

2 Answers 2

1

For the warning, it isn't actually working. A single if statement is expecting a single boolean, yet you try to compare data$Estimate (a vector) to "*" (a single element). It therefore does exactly what it says in the warning, takes the first element only of data$Estimate. Your thought process was good, just didn't quite hit the implementation!

ifelse() allows for vectorization (i.e. a vector of booleans), so it does what you thought the if-else should do. No need for sapply in this case, we can just vectorize.

replace vect below with your data$Estimate

vect<-c("*", "X", "*", "*", "10YEAH", "WHAT", "BlurbBlurb")
vect<-ifelse(vect=="*","Yes", "No" )
vect

#[1] "Yes" "No"  "Yes" "Yes" "No"  "No"  "No" 
Sign up to request clarification or add additional context in comments.

Comments

0

In your column Estimate there are more than one entries containing "*". But if statement uses one logical element only like:

any(data.set$Estimate=="*")

And seeing that you want to replace enteries having * with "YES" you can use

my.fun1<-function(x)
         {
            ifelse(x=="*","YES","NO")
         }
data.set$Estimate<-sapply(data.set$Estimate,my.fun1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.