Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

r - Test for NA and select values based on result

My question is rather simple. What I want is if A[i]!=NA, then C[i]=A[i], if A[i]=NA, then C[i]=B[i], however, I always get some error messages. Can somebody help me out?

A   B   C
NA  82.6    .
NA  127.2   .
NA  93.6    .
NA  105 .
NA  104 .
NA  90.6    .
NA  95.8    .
NA  103 .
NA  85.4    .
NA  81.5    .
NA  142.8   .
NA  102.3   .
NA  104 .
NA  103 .
NA  94.6    .
NA  113.8   .
NA  113.5   .
NA  74.5    .
NA  123.8   .
NA  94  .
NA  89.8    .
NA  74  .
NA  104 .
NA  100.5   .
NA  102.9   .
NA  132.5   .
NA  91  .
NA  92.5    .
NA  97  .
NA  90  .
54.6    51.7    .
NA  61  .
NA  80  .
NA  77.5    .
NA  NA  .
NA  80.6    .
NA  44.6    .
NA  37.6    .
NA  27  .
NA  NA  .
NA  NA  .
NA  NA  .
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use is.na :

DF <- within(DF,
   C <- ifelse(!is.na(A),A,B)
)

with DF being your dataframe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...