将列粘贴在一起而NA不会成为字符

时间:2018-10-11 06:24:15

标签: r na

我有一个很大的数据集,其中包含多个缺失和重复的值。我的首要目标是创建一个新列(Name),该列由三个现有列组成,例如FirstNameMiddleInitialLastName

我尝试过:

owners4$Name <- paste(owners4$FirstName, owners4$MiddleInitial, owners4$LastName)

,但是这导致NA被粘贴为字符,而不仅仅是NA。 之后,我将删除在新列中具有NA的每一行。

有人确定我可以实现这一目标吗?

2 个答案:

答案 0 :(得分:1)

这是一种使用带有anyNA()的名称成分向量的方法:

FirstName <- "John"
MiddleInitial <- NA
LastName <- "Jones"
name <- c(FirstName, MiddleInitial, LastName)

x <- ifelse(anyNA(name), NA, paste(name, collapse=" "))
x
[1] NA

MiddleInitial <- "P"
name <- c(FirstName, MiddleInitial, LastName)
x <- ifelse(anyNA(name), NA, paste(name, collapse=" "))
x
[1] "John P Jones"

Demo

答案 1 :(得分:1)

使用na.omit粘贴列,请参见示例:

# reproducible example
owners4 <- data.frame(FirstName = c("Aa", "Bb", NA),
                      MiddleInitial = c("T", "U", NA),
                      LastName = c(NA, "Yyy", NA))

owners4$Name <- apply(owners4[, c("FirstName", "MiddleInitial", "LastName")], 1,
                      function(i){ paste(na.omit(i), collapse = " ") })

owners4
#   FirstName MiddleInitial LastName     Name
# 1        Aa             T     <NA>     Aa T
# 2        Bb             U      Yyy Bb U Yyy
# 3      <NA>          <NA>     <NA>         

现在过滤掉名称为空的行

result <- owners4[ owners4$Name != "", ]
result
#   FirstName MiddleInitial LastName     Name
# 1        Aa             T     <NA>     Aa T
# 2        Bb             U      Yyy Bb U Yyy