我有一个包含 city、state 和 country 列的数据框。我想创建一个串联的字符串:“城市、州、国家”。但是,我的其中一个城市没有州(取而代之的是 NA
)。我希望那个城市的字符串是“城市,国家”。这是创建错误字符串的代码:
# 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,
,这是不需要的:> 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 = ", "
.
最佳答案
另一种方法是事后修复它:
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
就使用 apply叫 dff
:apply(dff, 1, function(x) paste(na.omit(x),collapse=", ") )
关于r - 当其值在 R 中为 NA 时如何跳过 paste() 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22854112/