0

I have the following problem

df <- df %>% mutate(col1=ifelse(col2>1 ,0,3))

If I have col2 = null, then the result is null. I tried

df <- df %>% mutate(col1=ifelse(col2>1 | is.na(col2)==FALSE ,0,3))
df <- df %>% mutate(col1=ifelse(col2>1 | is.null(col2)==FALSE ,0,3))

Yet, the outcome is the same. How to get 3 if col2 = null?

Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    Try to compare to a string: `col2 == "null"`, provide example data, it all depends on what you mean by null. For example, test: `is.null(NULL)` vs `is.null(null)` vs `is.null("null")`. – zx8754 Mar 02 '22 at 13:47
  • 1
    R is case sensitive, are you talking about `null` or `NULL`? Also, explicit comparisons to `FALSE` or `TRUE` don't make much sense since the values to be compared already are logical values, instead of `is.na(col2)==FALSE` it's better to test `!is.na(col2)` – Rui Barradas Mar 02 '22 at 13:49
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Columns of data.frames in R can't contain actual "NULL" values usually, so something odd seems to be going on for them to be there in the first place. – MrFlick Mar 02 '22 at 15:16
  • 1
    Please share sample data. Data frames can't really contain `NULL` values, so it's not clear what you actually have. (For example `df1 = data.frame(x = 1:3)`, if you try to introduce `df1$x[1] <- NULL`, there is an error and `df1` is unchanged). – Gregor Thomas Mar 02 '22 at 15:16
  • `dput()` is probably the best way to share sample data - it is copy/pasteable and includes all class and structure information. For example `dput(df[1:5, ])` for the first 5 rows. Choose a small subset that includes some of the "null" values giving you trouble. And also please be clear about the desired result. What do you want `col1` to be in the case where `col2` is `NA`? – Gregor Thomas Mar 02 '22 at 15:22

1 Answers1

0

Here a sample dataframe:

df <- data.frame(col1 = c(1,2,3,4,5),
                 col2 = I(list(2, NULL, NULL, 5, 2)))
df

With output:

 col1 col2
    1    2
    2     
    3     
    4    5
    5    2

To replace the NULL in col2 with 3 you can use the following code:

df <- df %>% replace(.=="NULL", 3)

Which results in this:

 col1 col2
    1    2
    2    3
    3    3
    4    5
    5    2
Quinten
  • 35,235
  • 5
  • 20
  • 53