如何在ifelse中包含NA? [英] How to include NA in ifelse?
问题描述
我正在尝试根据其他列的值的逻辑语句创建列 ID
。例如,在以下数据框中
I am trying to create a column ID
based on logical statements for values of other columns. For example, in the following dataframe
test <- structure(list(time = c(10L, 20L, NA, 30L), type = structure(c(1L,
2L, 3L, NA), .Label = c("A", "B", "C"), class = "factor"), ID = c(NA,
"1", NA, NA)), .Names = c("time", "type", "ID"), row.names = c(NA,
-4L), class = "data.frame")
看起来像
time type
1 10 A
2 20 B
3 NA C
4 30 NA
我想创建一个包含值1的新列 ID
所有时间
不是 NA
以及所有类型
不是 A
。我使用以下代码:
I want to make a new column ID
containing a value of 1 for all time
that are not NA
and all type
that are not A
. I am using the following code for this:
test$ID <- ifelse(is.na(test$time) | test$type == "A", NA, "1")
这样的结果为
time type ID
1 10 A NA
2 20 B 1
3 NA C NA
4 30 NA NA
但是,此代码忽略 NA列
,在中的
类型 NA
的值> ID 。我需要这个值为1,所以我需要的解决方案应该给:
However, this code ignores the NA
in column type
, resulting in a value of NA
in column ID
. I need this to be a value of 1, so my needed solution should give:
time type ID
1 10 A NA
2 20 B 1
3 NA C NA
4 30 NA 1
谁能告诉我怎么做这个?如果我能以某种方式更改 is.na(test $ type)
的结果以返回 FALSE,我可以使用现有代码code>而不是
TRUE
,但我不知道该怎么做。或者,我现有代码的结构可能需要完全改变?我感谢任何帮助!
Can anyone tell me how I might do this? I could get this to work with my existing code if I could somehow change the result of is.na(test$type)
to return FALSE
instead of TRUE
, but I'm not sure how to do that. Or, maybe the structure of my existing code needs to be entirely changed? I appreciate any help!
推荐答案
你无法真正比较 NA
使用其他值,因此使用 ==
将无效。请考虑以下因素:
You can't really compare NA
with another value, so using ==
would not work. Consider the following:
NA == NA
# [1] NA
您只需将您的比较从 ==
更改为% in%
:
You can just change your comparison from ==
to %in%
:
ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
# [1] NA "1" NA "1"
关于你的其他问题,
Regarding your other question,
我可以让这个工作使用我现有的代码,如果我能以某种方式更改
的结果is.na(test $ type)
返回FALSE
TRUE
,但我不知道该怎么做。
I could get this to work with my existing code if I could somehow change the result of
is.na(test$type)
to returnFALSE
instead ofTRUE
, but I'm not sure how to do that.
只需使用!
来否定结果:
!is.na(test$time)
# [1] TRUE TRUE FALSE TRUE
这篇关于如何在ifelse中包含NA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!