我有一个很大的数据集,其中包含多个缺失和重复的值。我的首要目标是创建一个新列(Name
),该列由三个现有列组成,例如FirstName
,MiddleInitial
和LastName
。
我尝试过:
owners4$Name <- paste(owners4$FirstName, owners4$MiddleInitial, owners4$LastName)
,但是这导致NA
被粘贴为字符,而不仅仅是NA。
之后,我将删除在新列中具有NA
的每一行。
有人确定我可以实现这一目标吗?
答案 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"
答案 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