elliot
elliot

Reputation: 1944

Using if_else, I can't return the column used as the conditional if the conditional is false

I've created a flag variable of different job descriptions in a dataset. I would like to change the each flag==true into the same row position from another variable.

I've tried ifelse and if_else; but all I've been able to get is a list of the changed values for the true conditional and NAs.

Here is a reproducible example using diamonds:

mydata <- diamonds[1:10,c(3,4)] 
mydata$position <- c('flag','cathy')
mydata
mydata$new.vary <- mydata %>% if_else(color=='E',position,color)

Upvotes: 3

Views: 3517

Answers (1)

Benjamin
Benjamin

Reputation: 17359

You seem to be mixing dplyr and base R frameworks.

In base R, you would use

mydata$new.vary <- ifelse(mydata$color == 'E', mydata$position, mydata$color)

This works, but you should take note that mydata$position is a character object, and mydata$color is a factor, which is represented internally as an integer. If you try to run the same code with if_else from the dplyr package, you'll get the following:

mydata$new.vary <- if_else(mydata$color == 'E', mydata$position, mydata$color)
Error: `false` must be type character, not integer

if_else is a little more strict than ifelse, requiring that both the true and false arguments have the same type.

If you want to use the dplyr approach, you can use

mydata %>% 
  mutate(new.vary = ifelse(color == 'E', position, color))

or, if you want to use dplyr's if_else, try

mydata %>% 
  mutate(color = as.character(color),
         new.vary = if_else(color == 'E', position, color))

Upvotes: 8

Related Questions