I am trying to add a new column based on values in another column. (Basically if the other column is missing or 0, set the new value to 0 or to 1)
What's wrong with this code below?
times=nrow(eachfile)
for(i in 1:times)
{eachfile$SalesCycleN0[i] <- ifelse(eachfile$R[i]==NA | eachfile$R[i]==0,0,1 ) }
table(eachfile$SalesCycleN0)
As long as you have tested that the column only contains 0, 1 and NA I would do:
A more efficient way of doing this is using the
sapply
function, rather than using afor
loop (handy in case of huge dataset). Here is an example:In your case:
Nothing is ever "==" to NA. Just do this (no loop):
If you were looking for a little more economy in code this might also work:
grepl
returns FALSE for NA's.