如何评估R中if语句中的NA值?

时间:2015-10-05 13:05:04

标签: r if-statement na

我有一个数据集,我需要使用IF语句来评估第5列中的每个值。如果它是积极的,它应该说' Up'否则它应该说'不起来'。问题是,在每天结束时,我会有5个NA值,而我的陈述不知道如何评估这些值。我的数据集看起来像:

 379    949 2115    2015-02-20  0   Not Up
 380    950 2115    2015-02-20  -5  Not Up
 381    951 2115    2015-02-20  -5  Not Up
 382    952 2115    2015-02-20  -5  Not Up
 383    953 2115    2015-02-20  -5  Not Up
 384    954 2115    2015-02-20  -5  Not Up
 385    955 2110    2015-02-20  0   Not Up
 386    956 2110    2015-02-20  NA  Up
 387    957 2110    2015-02-20  NA  Up
 388    958 2110    2015-02-20  NA  Up
 389    959 2110    2015-02-20  NA  Up
 390    960 2110    2015-02-20  NA  Up
 391    571 2075    2015-02-23  15  Up
 392    572 2075    2015-02-23  15  Up
 393    573 2085    2015-02-23  0   Up
 394    574 2085    2015-02-23  -5  Up
 395    575 2085    2015-02-23  -5  Up
 396    576 2090    2015-02-23  -15 Up
 397    577 2090    2015-02-23  -20 Up

如您所见,在NA值之后,If语句无法评估并正确输出我需要的内容。

任何有关如何处理“NA'价值将非常感谢!

2 个答案:

答案 0 :(得分:4)

您可以使用CREATE TABLE test ( Cola VARCHAR(50) ); INSERT INTO test VALUES ('414F2D363030323831'); INSERT INTO test VALUES ('123456789'); INSERT INTO test VALUES ('123456789D'); INSERT INTO test VALUES ('A123456789'); 来处理这种额外的情况:

Cola
--------------------
414F2D363030323831
123456789D
A123456789

如果您想要对NA值说“Not Up”,请使用:

ifelse

答案 1 :(得分:1)

假设你想要" Not up"对于NAs值:

df$x6 <- ifelse(df$x5 > 0 & !is.na(df$x5), "Up", "Not Up")

输出:

    x1  x2   x3         x4  x5     x6
1  379 949 2115 2015-02-20   0 Not Up
2  380 950 2115 2015-02-20  -5 Not Up
3  381 951 2115 2015-02-20  -5 Not Up
4  382 952 2115 2015-02-20  -5 Not Up
5  383 953 2115 2015-02-20  -5 Not Up
6  384 954 2115 2015-02-20  -5 Not Up
7  385 955 2110 2015-02-20   0 Not Up
8  386 956 2110 2015-02-20  NA Not Up
9  387 957 2110 2015-02-20  NA Not Up
10 388 958 2110 2015-02-20  NA Not Up
11 389 959 2110 2015-02-20  NA Not Up
12 390 960 2110 2015-02-20  NA Not Up
13 391 571 2075 2015-02-23  15     Up
14 392 572 2075 2015-02-23  15     Up
15 393 573 2085 2015-02-23   0 Not Up
16 394 574 2085 2015-02-23  -5 Not Up
17 395 575 2085 2015-02-23  -5 Not Up
18 396 576 2090 2015-02-23 -15 Not Up
19 397 577 2090 2015-02-23 -20 Not Up

数据:

df <- structure(list(x1 = 379:397, x2 = c(949L, 950L, 951L, 952L, 953L, 
954L, 955L, 956L, 957L, 958L, 959L, 960L, 571L, 572L, 573L, 574L, 
575L, 576L, 577L), x3 = c(2115L, 2115L, 2115L, 2115L, 2115L, 
2115L, 2110L, 2110L, 2110L, 2110L, 2110L, 2110L, 2075L, 2075L, 
2085L, 2085L, 2085L, 2090L, 2090L), x4 = structure(c(1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L), .Label = c("2015-02-20", "2015-02-23"), class = "factor"), 
    x5 = c(0L, -5L, -5L, -5L, -5L, -5L, 0L, NA, NA, NA, NA, NA, 
    15L, 15L, 0L, -5L, -5L, -15L, -20L)), .Names = c("x1", "x2", 
"x3", "x4", "x5"), class = "data.frame", row.names = c(NA, -19L
))