jeudi 23 septembre 2021

Ifelse condition without creating NA's

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!

Aucun commentaire:

Enregistrer un commentaire