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

折月煮酒 提交于 2019-12-17 19:45:51

问题


I have a data frame with the columns city, state, and country. I want to create a string that concatenates: "City, State, Country". However, one of my cities doesn't have a State (has a NA instead). I want the string for that 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 display dff$string, I get the following. Note that the last string has a 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 do I do to skip that NA,, including the sep = ", ".


回答1:


The alternative is to just fix it up afterwards:

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"   

Alternative #2, is to use apply once you have your data.frame called dff:

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


来源:https://stackoverflow.com/questions/22854112/how-to-skip-a-paste-argument-when-its-value-is-na-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!