Reputation: 21
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)
Upvotes: 2
Views: 17392
Reputation: 1125
As long as you have tested that the column only contains 0, 1 and NA I would do:
eachfile$SalesCycleN0 <- 1
eachfile$SalesCycleN0[is.na(eachfile$R) | eachfile$R==0] <- 0
Upvotes: 5
Reputation: 8858
A more efficient way of doing this is using the sapply
function, rather than using a for
loop (handy in case of huge dataset). Here is an example:
df = data.frame(x = c(1,2,0,NA,5))
fun = function(i) {is.na(df$x[i]) || (df$x[i] == 0)}
bin <- (sapply(1:nrow(df), FUN = fun))*1 ## multiplying by 1 will convert the logical vector to a binary one.
df <- cbind(df, bin)
In your case:
fun = function(i) {is.na(eachfile$SalesCycleNO[i]) || (eachfile$SalesCycleNO[i] == 0)}
bin <- (sapply(1:times, FUN = fun))*1
eachfile <- cbind(eachfile, bin)
Upvotes: 2
Reputation: 263481
Nothing is ever "==" to NA. Just do this (no loop):
eachfile$SalesCycleN0 <- ifelse( is.na(eachfile$R) | eachfile$R==0, 0,1 )
If you were looking for a little more economy in code this might also work:
eachfile$SalesCycleN0 <- as.numeric( !grepl("^0$", eachfile$R) )
grepl
returns FALSE for NA's.
Upvotes: 2