我正在尝试优化循环,但遇到一个问题,但在这里没有找到任何直接的解决方案。我已经签出了其他线程,例如Error in if/while (condition) {: missing Value where TRUE/FALSE needed,但这并不能帮助我解决问题,但我仍然遇到相同的问题。
这是我的代码:
output <- character (nrow(df)) # predefine the length and type of the vector
condition <- (df$price < df$high & df$price > df$low) # condition check outside the loop
system.time({
for (i in 1:nrow(df)) {
if (condition[i]) {
output[i] <- "1"
}else if (!condition[i]){
output[i] <- "0"
}else {
output[i] <- NA
}
}
df$output <- output
})
我基本上是在检查我的价格是否在一定范围内。如果它在范围内,我给它分配1,如果它在范围内,我给它分配0。但是,我有几个NA值,然后当我到达NA时,我的循环停止。
如果我过滤掉NA,您将在下面看到工作代码。但是我想有一种可以处理NA的方法。
df<- df%>% filter(!is.na(price))
output <- character (nrow(df)) # predefine the length and type of the vector
condition <- (df$price < df$high & df$price > df$low) # condition check outside the loop
system.time({
for (i in 1:nrow(df)) {
if (condition[i]) {
output[i] <- "1"
}else {
output[i] <- "0"
}
}
df$output <- output
})
任何想法我如何处理NA?
R中的if / else不喜欢NA。您可以尝试一下,从检查输入中的NA条件开始,然后检查条件的TRUE或FALSE。
output <- character (nrow(df)) # predefine the length and type of the vector
condition <- (df$price < df$high & df$price > df$low) # condition check outside the loop
system.time({
for (i in 1:nrow(df)) {
if(is.na(condition[i])){
output[i] <- NA
}else (condition[i]) {
output[i] <- "1"
}else{
output[i] <- "0"
}
}
df$output <- output
})
我认为您可以做到:
df$output <- as.integer(df$price < df$high & df$price > df$low)
这将处理所有情况。
例如
df <- data.frame(price = c(10, 23, NA, 50), high = 25, low = 5)
df$output <- as.integer(df$price < df$high & df$price > df$low)
df
# price high low output
#1 10 25 5 1
#2 23 25 5 1
#3 NA 25 5 NA
#4 50 25 5 0
我们也可以这样做
df$output <- +(df$price < df$high & df$price > df$low)