Using unite and str_to_title: NAs united as strings and go undetected as NAs R

Viewed 86

I have NAs in two columns that were united. Before uniting, I used str_to_title to create uniformity in the values.

The issue is that now the NAs are not registered as NAs and they've united as strings. I.E.

City         State        City, State
Denver        CO          Denver, CO
NA            NA          NA, NA
Los Angeles   CA          Los Angeles, CA

I tried hard coding it using df[df$col == "NA, NA"] <- NA and that didn't work.

2 Answers

We can create an index and then update

library(stringr)
i1 <- !(is.na(df$City) & is.na(df$State))
df$City_State[i1] <- with(df[i1,], paste(City, State, sep=', '))

If we use str_c, then it would return NA if there is any NA

with(df, str_c(City, State, sep=", "))
#[1] "Denver, CO"      NA                "Los Angeles, CA"

data

df <- structure(list(City = c("Denver", NA, "Los Angeles"),
State = c("CO", 
NA, "CA")), class = "data.frame", row.names = c(NA, -3L))

We can use tidyr::unite with na.rm = TRUE to ignore NA values. while pasting.

tidyr::unite(df, CityState, City, State, na.rm = TRUE, remove = FALSE, sep = ",")

#       CityState        City State
#1      Denver,CO      Denver    CO
#2                       <NA>  <NA>
#3 Los Angeles,CA Los Angeles    CA

Make sure that City and State are of type characters and not factors when using unite.

Related