【问题标题】:How to skip a paste() argument when its value is NA in R如何在 R 中的值为 NA 时跳过 paste() 参数
【发布时间】:2014-04-04 05:15:32
【问题描述】:

我有一个包含城市、州和国家/地区列的数据框。我想创建一个连接:“城市,州,国家”的字符串。但是,我的一个城市没有州(取而代之的是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 = ", "

【问题讨论】:

  • 如果您有多个包含 NA 的列,则在粘贴 here 中有一个关于抑制 NA 的一般性讨论。

标签: r dataframe paste na


【解决方案1】:

另一种方法是事后修复它:

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:

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

【讨论】:

  • 我打算给出一个两管齐下的答案,但 有人 拿了第一部分作为他们自己的答案 ;-)
  • 实际上,我会对每个人的表现感兴趣,以及可能的陷阱......
【解决方案2】:

聚会迟到了,但unite 提供了一个步骤:

dff %>% unite("string", c(city, state, country), sep=", ", remove = FALSE, na.rm = TRUE)
                              string           city     state       country
1        Austin, Texas, United States         Austin     Texas United States
2 Knoxville, Tennessee, United States      Knoxville Tennessee United States
3 Salk Lake City, Utah, United States Salk Lake City      Utah United States
4                   Prague, Czech Rep         Prague      <NA>     Czech Rep

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多