函数中的R:当最后一个值为NA时出现意外错误
在R中使用within()函数时,我遇到了一些意外的行为。I(最终!)跟踪到数据帧中特定列的最后一个元素包含NA的情况 我简化了代码,创建了一个可复制的示例。显然,我遇到这种情况的实际应用程序要复杂得多(数据帧>500k行400列,>100行inwithin(),等等),而且避免使用inwithin()非常不方便 这与预期的效果一样:函数中的R:当最后一个值为NA时出现意外错误,r,R,在R中使用within()函数时,我遇到了一些意外的行为。I(最终!)跟踪到数据帧中特定列的最后一个元素包含NA的情况 我简化了代码,创建了一个可复制的示例。显然,我遇到这种情况的实际应用程序要复杂得多(数据帧>500k行400列,>100行inwithin(),等等),而且避免使用inwithin()非常不方便 这与预期的效果一样: fooTest <- data.frame(Group = c("Shell", NA, "Cup", NA, NA),
fooTest <- data.frame(Group = c("Shell", NA, "Cup", NA, NA),
CupComposition = c("Metal", NA, "Polyethylene", NA, "Test"),
LinerComposition = c("Polyethylene", NA, NA, NA, "Test"))
fooTest$Bearing <- NA
fooTest$Bearing[which(fooTest$Group=="Cup")] <-
as.character(fooTest$CupComposition[which(fooTest$Group=="Cup")])
fooTest$Bearing[which(fooTest$Group=="Shell")] <-
as.character(fooTest$LinerComposition[which(fooTest$Group=="Shell")])
fooTest$Bearing
fooTest关于在
中使用的错误消息,您可以尝试:
within(fooTest, {Bearing <- NA
Bearing[Group=='Cup' & !is.na(Group)] <-
as.character(CupComposition)[Group=='Cup' & !is.na(Group)]
Bearing[Group=='Shell' & !is.na(Group)] <-
as.character(LinerComposition)[Group=='Shell' & !is.na(Group)]
})
在这种情况下,我倾向于使用“%in%”;它可以更好地处理NAs:
fooTest <- data.frame(Group = c("Shell", NA, "Cup", NA, NA),
CupComposition = c("Metal", NA, "Polyethylene", NA, "Test"),
LinerComposition = c("Polyethylene", NA, NA, NA, "Test"))
fooTest <- within(fooTest, {
Bearing <- NA
Bearing[Group %in% "Cup"] <-
as.character(CupComposition[Group %in% "Cup"])
Bearing[Group %in% "Shell"] <-
as.character(LinerComposition[Group %in% "Shell"])
})
fooTest Tryinthein(fooTest,{非常感谢你的快速回答。这很有效。如果你把它作为答案,我会接受它。我想寓意是当存在NA值时,避免在()内使用which()(首先使用which()的原因!)我将此作为一个答案,并为您的大数据集提供了一个可能的解决方案。非常感谢。在这种情况下,为了便于阅读,我想我将使用更简单的解决方案,因为()中只有10行涉及which()。但是,我相信有人会发现更复杂的答案很有用。非常感谢。这非常简洁,并且可以扩展到多个值以进行匹配(虽然在本例中不需要)。函数的最佳选择通常取决于哪个函数处理得更好!
fooTest1 <- fooTest
fooTest1[] <- lapply(fooTest1, as.character)#convert the columns to character class
Un1 <- sort(unique(na.omit(fooTest1$Group)))
m1 <- do.call(cbind,Map(function(v, x,y)
ifelse(v==y & !is.na(v), x, NA) , list(fooTest1[,1]),
fooTest1[,-1], Un1))
indx1 <- which(!is.na(m1), arr.ind=TRUE)[,1]
fooTest1$Bearing <- NA
fooTest1$Bearing[indx1] <- m1[!is.na(m1)]
fooTest1
# Group CupComposition LinerComposition Bearing
#1 Shell Metal Polyethylene Polyethylene
#2 <NA> <NA> <NA> <NA>
#3 Cup Polyethylene <NA> Polyethylene
#4 <NA> <NA> <NA> <NA>
#5 <NA> Test Test <NA>
fooTest <- data.frame(Group = c("Shell", NA, "Cup", NA, NA),
CupComposition = c("Metal", NA, "Polyethylene", NA, "Test"),
LinerComposition = c("Polyethylene", NA, NA, NA, "Test"))
fooTest <- within(fooTest, {
Bearing <- NA
Bearing[Group %in% "Cup"] <-
as.character(CupComposition[Group %in% "Cup"])
Bearing[Group %in% "Shell"] <-
as.character(LinerComposition[Group %in% "Shell"])
})