-3

I have to apply condition to two columns in order to get a new column with 1 and 0's, I want the NA's in column1 to be retained as NA's in the new column. How do I do it in R?

This is code

df$newcolumn <- ifelse(((df$col1 %in% ("eat")) |
      (df$col2 %in% ("yes"))), 1,  0)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
ret24
  • 15
  • 1
  • 1
    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. – MrFlick Jul 04 '20 at 07:48

2 Answers2

2

Try this. To keep the NAs add another ifelse which checks for NAs in col1 and keeps them.

df <- structure(list(col1 = c(
  NA, "drink", "drink", "drink", "eat",
  "eat", "eat", NA, "eat", "drink"
), col2 = c(
  "yes", "yes", "no",
  "no", "yes", "yes", "yes", "yes", "no", "yes"
), newcolumn = c(
  NA,
  "1", "0", "0", "1", "1", "1", NA, "1", "1"
)), row.names = c(
  NA,
  -10L
), class = "data.frame")

df$newcolumn <- ifelse(is.na(df$col1), df$col1, ifelse(df$col1 %in% ("eat") | df$col2 %in% ("yes"), 1, 0))
df
#>     col1 col2 newcolumn
#> 1   <NA>  yes      <NA>
#> 2  drink  yes         1
#> 3  drink   no         0
#> 4  drink   no         0
#> 5    eat  yes         1
#> 6    eat  yes         1
#> 7    eat  yes         1
#> 8   <NA>  yes      <NA>
#> 9    eat   no         1
#> 10 drink  yes         1
stefan
  • 90,330
  • 6
  • 25
  • 51
0

You can try :

library(dplyr)

df %>%
  mutate(newcolumn = case_when(is.na(col1) ~ NA_integer_, 
                               col1 == 'eat' | col2 == 'yes' ~ 1L, 
                               TRUE ~ 0L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks Ronak Shah, I have "yes" and "no" in col2, In the new column I want "no" and "eat" also to be 1. The above code makes it 0 instead. – ret24 Jul 04 '20 at 09:11
  • @a24 Please don't extend the question in comments, edit your question to include the conditions you want. Also please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269) so that it is easier to help you. – Ronak Shah Jul 04 '20 at 09:19