R: If operator function using

I have the following framework:

ID  Value
1    0
2   100
3   200
4    0

      

I want to write a function that produces "Hello" if the value in the "Value" column is 0, otherwise "Bye". The result should be:

Answer
Hi
Bye
Bye
Hi

      

Here is the code I tried:

Type <- function(df){
  if(df$Value == 0)
    "Hi"
  else
    "Bye"
}

apply(X = df, MARGIN = 1, FUN = Type)

      

However, I am getting this error:

Error in Test_Customer$Pipe : $ operator is invalid for atomic vectors

      

Can anyone help me fix this error? Thank you!

+3


source to share


2 answers


apply()

is intended for use with matrices, not data frames. It will actually convert your data.frame to a matrix. So when it is executed, it traverses in rows or columns as simple atomic vectors. It does not augment data.frames. You cannot use $

with atomic vectors, hence your error message.

You don't need one apply()

for your example. Simple ifelse()

will work



ifelse(df$Value==0, "Hi,"Bye")

      

The function is ifelse()

vectorized to work on a column of data at a time. (The operator is if

not vectorized).

+2


source


You may try

 c('Bye', 'Hi')[(df1$Value==0)+1L]
 #[1] "Hi"  "Bye" "Bye" "Hi" 

      



Or use factor

factor(df1$Value!=0, labels=c('Hi', 'Bye'))
#[1] Hi  Bye Bye Hi 
#Levels: Hi Bye

      

+2


source







All Articles