简体   繁体   English

如何在分配值时处理 NA

[英]How to handle NAs while assigning values

I have a data frame x which includes two variables fdhm1 and fdhm2 .我有一个数据框x ,其中包含两个变量fdhm1fdhm2 Now, I want to generate a new variable fdhm conditional on both values of fdhm1 and fdhm2 .现在,我要生成一个新的变量fdhm上的两个值条件fdhm1fdhm2

Specifically, if fdhm1 != NA and fdhm2 ==0 , fdhm <- fdhm1 .具体来说,如果fdhm1 != NAfdhm2 ==0fdhm <- fdhm1 Otherwise, fdhm <- NA .否则, fdhm <- NA

Here is my codes:这是我的代码:

fdhm   <- NA
x   <- cbind(x,fdhm)
use   <- x$fdhm1 != NA & x$fdhm2 == 0
x$fdhm[use]   <- x$fdhm1[use]

but an error message popped up, saying that NAs are not allowed in subscripted assignments但是弹出了一条错误消息,说在下标赋值中不允许使用 NA

I am not sure what the reason is?我不确定是什么原因?

You can try !is.na(x$fdhm1) (rather than x$fdhm1 != NA ), eg,您可以尝试!is.na(x$fdhm1) (而不是x$fdhm1 != NA ),例如,

x <- within(x,fdhm <- ifelse(!is.na(fdhm1)&fdhm2==0,fdhm1,NA))

Here is an example showing you what happened.这是一个示例,向您展示发生了什么。

Given a vector u like below给定一个向量u下方喜欢

> u
[1] NA  2 NA  1 NA

then然后

> u!=NA
[1] NA NA NA NA NA

> !is.na(u)
[1] FALSE  TRUE FALSE  TRUE FALSE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM