r - How can I pass NA when attempt to select fails with "attempted to select less than one element"? -



r - How can I pass NA when attempt to select fails with "attempted to select less than one element"? -

i have 2 info frames, , b, both have "state" , "year" columns (as others). i'm trying transfer value varx b a. used this:

for(i in seq_along(a)) {a$varx[[i]]<-b$varx[[which(b$state==a$state[[i]] & b$year==a$year[[i]])]]}

i error:

error in b$varx[[which(b$state == a$state[[i]] & b$year == : effort select less 1 element

the problem seems there rows in a without corresponding row in b, can't select element. how can either homecoming na in cases (so a$varx[i]=na), or clean cases there's no corresponding rows in b?

loop not choice. see working example:

a=data.frame(state=c("a","b","a"),year=c("2012","2013","2014"),varx=c(1,2,3)) ################### state year varx 1 2012 1 2 b 2013 2 3 2014 3 ################### b=data.frame(state=c("a","b","c"),year=c("2012","2013","2014"),varx=c(4,5,6)) ################### state year varx 1 2012 4 2 b 2013 5 3 c 2014 6 ################### # merge , b c=merge(a,b,by=c("state","year"),all.x=t,sort =f,suffixes = c(".a","")) ################### state year varx.a varx 1 2012 1 4 2 b 2013 2 5 3 2014 3 na ################### # drop varx in info frame subset(c,select=-varx.a) ################### state year varx 1 2012 4 2 b 2013 5 3 2014 na ###################

r for-loop

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -