How to skip paste () when its value is NA in R

I have a data frame with columns of the city, state and country. I want to create a line that combines: "City, state, country." However, in one of my cities there is no state (there is instead NA). I want the line for this city to be "City, country." Here is the code that creates the wrong string:

# define City, State, Country
  city <- c("Austin", "Knoxville", "Salk Lake City", "Prague")
  state <- c("Texas", "Tennessee", "Utah", NA)
  country <- c("United States", "United States", "United States", "Czech Rep")
# create data frame
  dff <- data.frame(city, state, country)
# create full string
  dff["string"] <- paste(city, state, country, sep=", ")

When I show dff$string, I get the following. Please note: the last line has NA,which is not needed:

> dff["string"]
                               string
1        Austin, Texas, United States
2 Knoxville, Tennessee, United States
3 Salk Lake City, Utah, United States
4               Prague, NA, Czech Rep

What should I do to skip this one NA,, including sep = ", ".

+4
source share
1 answer

:

gsub("NA, ","",dff$string)

#[1] "Austin, Texas, United States"       
#[2] "Knoxville, Tennessee, United States"
#[3] "Salk Lake City, Utah, United States"
#[4] "Prague, Czech Rep"   

№ 2 - , data.frame, dff:

apply(dff, 1, function(x) paste(na.omit(x),collapse=", ") )
+7

Source: https://habr.com/ru/post/1534965/


All Articles