Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Why are the NAs being ignored while I'm using the ifelse/mutate functions?

$
0
0

So I have a data frame with several occurences of different species and a "new_name" empty column that I want to fill with mutate/ifelse. Basically I want the new_name to be filled according to these conditions: if the status is unaccepter I want the new_name to be the value of "valid_name" and if the status is accepted or NA I want the new_name to take the value of "species". This is an example of how my data frame is structured: ´´´

example of the data frame

         species           valid_name                 new_name    status
1.  Tilapia guineensis |         NA                 |  NA       | NA

2.     Tilapia zillii  |  Hippocampus trimaculatus  |  NA       | unaccepted

3. Fundulus rubrifrons |  Hippocampus trimaculatus  |  NA       | unaccepted

4.  Eutrigla gurnardus |  Bougainvillia supercili   |  NA       | accepted

5.   Sprattus sprattus |        NA                  |  NA       | NA

6.        Gadus morhua |  Aglantha digitale         |  NA       | accepted

´´´

So far I tried the following:

df<-df%>%
  mutate(new_name = ifelse(status=="unaccepted",valid_name,ifelse(status=="accepted" | is.na(status),species,NA)))

So this code is working only for the values of "status" that don't have NAs. Otherwise it just ignores the NAs and does nothing. So the data frame becomes somthing like this:

             species           valid_name                 new_name    status
    1.  Tilapia guineensis |         NA                 |  NA                         | NA

    2.     Tilapia zillii  |  Hippocampus trimaculatus  |  Hippocampus trimaculatus   | unaccepted

    3. Fundulus rubrifrons |  Hippocampus trimaculatus  |  Hippocampus trimaculatus   | unaccepted

    4.  Eutrigla gurnardus |  Bougainvillia supercili   |  Eutrigla gurnardus         | accepted

    5.   Sprattus sprattus |        NA                  |  NA                         | NA

    6.        Gadus morhua |  Aglantha digitale         |  Gadus morhua               | accepted

Thanks in advance for any answers


Viewing all articles
Browse latest Browse all 201894

Trending Articles