ssk
ssk

Reputation: 1

Conditional Filtering using R

Consider the below given dataframe;

Sample DataFrame

| Name | Age | Type |
---------------------
| EF   | 50  |  A   |
| GH   | 60  |  B   |
| VB   | 70  |  C   |

Code to perform Filter

df2 <- df1 %>% filter(Type == 'C') %>% select(Name)

The above code will provide me a dataframe with singe column and row.

I would like to perform a conditional filter where if a certain type is not present it should consider the name to be NULL/NA.

Example

df2 <- df1 %>% filter(Type = 'D') %>% select(Name)

Must give an output of;

| Name |
--------
|  NA  |

Instead of throwing an error. Any inputs will be really helpful. Either DPLYR or any other methods will be appreciable.

Upvotes: 0

Views: 81

Answers (2)

kath
kath

Reputation: 7734

An approach with complete from tidyr would be:

library(dplyr)
library(tidyr)

df1 %>% 
  complete(Type = LETTERS) %>%  # Specify which Types you'd expect, other values are filled with NA
  filter(Type == 'D') %>% 
  select(Name)
# A tibble: 1 x 1
#   Name 
#   <fct>
# 1 NA 

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522636

Here is a base R approach:

name <- df[df$Name == "D", "Name"]
ifelse(identical(name, character(0)), NA, name)

[1] NA

Should the name not match to D, the subset operation would return character(0). We can compare the output against this, and then return NA as appropriate.

Data:

df <- data.frame(Name=c("EF", "GH", "VB"), 
                Age=c(50, 60, 70), 
                Type=c("A", "B", "C"),
                stringsAsFactors=FALSE)

Upvotes: 2

Related Questions