当R值中的值为NA时,如何跳过一个paste()参数 [英] How to skip a paste() argument when its value is NA in R
问题描述
我有一个包含城市,州和国家/地区的数据框。我想创建一个连接:城市,州,国家的字符串。但是,我的一个城市没有州(有一个 NA
而已)。我想要这个城市的字符串是城市,国家。以下是创建错误字符串的代码:
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=", ")
当我显示 dff $ string
时,我得到以下内容。请注意,最后一个字符串有一个 NA,
,这是不需要的:
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
我如何跳过 NA ,
,包括 sep =,
。
推荐答案
替代方法是稍后修复:
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"
另一种方法是使用 data.frame
调用 dff
:
Alternative #2, is to use apply once you have your data.frame
called dff
:
apply(dff, 1, function(x) paste(na.omit(x),collapse=", ") )
这篇关于当R值中的值为NA时,如何跳过一个paste()参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!