James Bradley
James Bradley

Reputation: 11

Filling in Value for NA with tidyverse

I am trying to fill in a specific NA value with 'NY'. This is my approach:

data %>% 
  filter(is.na(State) & City == 'New York') %>%
  select(State) <- 'NY'

I am getting the following error message:

Error in data %>% filter(is.na(State) & City == "New York") %>% select(State) <- "NY" : 
could not find function "%>%<-"

How can I fix this?

Upvotes: 0

Views: 541

Answers (2)

akrun
akrun

Reputation: 887741

We can use

library(dplyr)
data %>%
      mutate(State = case_when(is.na(State) & City == 'New York' ~ 'NY', 
            TRUE ~ State))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389225

Try using this :

data$State[is.na(data$State) & data$City == 'New York'] <- 'NY'

You can also use replace if you want to do this in dplyr pipe.


library(dplyr)
data %>% mutate(State = replace(State, is.na(State) & City == 'New York', 'NY')) 

Upvotes: 1

Related Questions