Home > OS >  Ifelse condition without creating NA's
Ifelse condition without creating NA's

Time:09-23

I am quite a beginner with R.

So i have a data.frame with Start times and Stop times. If the Start time ist > 1 AND the Stop time is < 5, i want to write a name in a new column. I have 15 different names in total with different conditions I want to excecute manually after one an other. For this, it is crucial, that no NAs are getting created when I consecute ifelse.

What I have so far:

data.frame$names <- ifelse(
  ( 
    (data.frame$Start >=1) &
      (data.frame$Stop<=5)
  ),
  print('Name'), 
  NA  
)

what can I put instead of NA, so it skips the rows which don't fulfill the condition?

I did not use if, because nothing happened. I used:

if (data.frame$Start => 1 && data.frame$Stop <=5) {data.frame$names = print ('Name')}

Here is a reproducible example:

Start<- c(1:10)
Stop<- c(2:11)
df=data.frame(Start,Stop)
df
   Start Stop
1      1    2
2      2    3
3      3    4
4      4    5
5      5    6
6      6    7
7      7    8
8      8    9
9      9   10
10    10   11

I would like to have a new column, that gives "name" to Start=>1 AND Stop<=5 and gives "name2" to Start>=5 AND Stop <= 10 so it looks like this:

    Start Stop Names
1      1    2  name
2      2    3  name
3      3    4  name
4      4    5  name
5      5    6 name2
6      6    7 name2
7      7    8 name2
8      8    9 name2
9      9   10 name2
10    10   11     

Thanks for your help!

CodePudding user response:

Here's an option using case_when -

library(dplyr)

df <- df %>%
  mutate(Names = case_when(Start >= 1 & Stop <= 5 ~ 'name', 
                           Start >= 5 & Stop <= 10 ~ 'name2', 
                           TRUE ~ ''))
df

#   Start Stop Names
#1      1    2  name
#2      2    3  name
#3      3    4  name
#4      4    5  name
#5      5    6 name2
#6      6    7 name2
#7      7    8 name2
#8      8    9 name2
#9      9   10 name2
#10    10   11      

CodePudding user response:

You can use '' to instead of NA:

data.frame$Names <- ifelse(((data.frame$Start >1) & (data.frame$Stop<5)),print('Name'),'')

Edit following comments: the dplyr solution below is elegant and easy to read. In base R, you could also embed two ifelse like this:

df$Names <- ifelse(((df$Start >=1) & (df$Stop<=5)),print('Name'),
              ifelse(((df$Start >=5) & (df$Stop<=10)),print('Name2'),''))

> df
   Start Stop Names
1      1    2  Name
2      2    3  Name
3      3    4  Name
4      4    5  Name
5      5    6 Name2
6      6    7 Name2
7      7    8 Name2
8      8    9 Name2
9      9   10 Name2
10    10   11 
  • Related