0

I've been using ifelse to assign a vector to a column of a dataframe, like this:

data[, ncol(data) + 1] <- ifelse(is.price, p, y) (where p and y are vectors)

Unfortunately, I realized that this expression vectorizes the first element of ifelse's return value, and so I get a column that's nrow(data) identical elements. Is this a flaw of R, and should I just use a more explicit assignment?

  • 1
    Can you show a small reproducible example with expectred output. What is `is.price` Are `is.price, p, y` of the same length? – akrun Apr 13 '19 at 14:05
  • `is.price` is a Boolean, `p` and `y` are numerical vectors of the same length – Lorenzo Naletto Apr 13 '19 at 14:09
  • 2
    what is the issue with that ifelse. I am not getting it – akrun Apr 13 '19 at 14:10
  • If you want help, please give a [mcve]. See [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269/4996248) for what this would mean in R. – John Coleman Apr 13 '19 at 14:31
  • The issue is that instead of returning vector `p` or `y`, I get the first element of `p` or `y` repeated `nrow(data)` times. – Lorenzo Naletto Apr 13 '19 at 14:42
  • 1
    `is.price` should be a Boolean vector of the same length as `p` and `y`. The length of `ifelse()` is the length of its first argument. If that argument has length 1, then so does the return value. You are taking that 1 return value and recycling it. You could just use something like `if(is.price) then data[, ncol(data) + 1] <- p else data[, ncol(data) + 1] <- y` – John Coleman Apr 13 '19 at 14:52
  • 4
    Lorenzo, I think @JohnColeman has the culprit for you. `ifelse` returns the same length as the conditional. If `is.price` can be the right length (not 1), then this will work. If `is.price` is length 1, you can instead use `data[...] <- if (is.price) p else v` (no `ifelse` required). (I typed this before John's edited comment updated ... but I think this version is more concise and readable than that one, though the result is the same.) – r2evans Apr 13 '19 at 14:59
  • 1
    @JohnColeman That's it thank you very much – Lorenzo Naletto Apr 13 '19 at 16:06

1 Answers1

0

Try :

library(dplyr)

data<- data %>%mutate( new_col= if_else(is.price, p, y))
  • Based on the comments (last one after you posted this answer), I suspect `dplyr::if_else` is not going to solve the problem; in fact, unless `ifelse` (which will happily misbehave), `if_else` will error if the length of `condition=` is not the same as either of `true=` or `false=`. (This is one of two ways I see `if_else` as *better* than `ifelse`, the other being enforcement of type/mode/class of the data.) – r2evans Apr 13 '19 at 17:07