lundi 5 février 2018

R: No error despite missing variable when using brackets, but there is with ifelse

While creating lead variables, I accidentally left out the lead variable by which my data is grouped. I was using brackets to insert an NA and there no was no error reported. To check my sanity, I did the same with ifelse and R created an error message. My concern is that if not for careful review, and some luck, I may never have known of my error.

How have others coded differently to make such less likely in the future (with minimal cost to time)? Also, are there other similar issues I should be aware of? Thanks, reproducible example is below.

dt <- data.frame(
group_name = c("D44", "D44","D44", "D45", "D45", "D47", "D47", "D47", "D47", "D48"),
order_number = sample(1:10))

dt$group_name <- as.character(dt$group_name) # so not a factor

dt <- dt[order(dt$group_name, dt$order_number),] # sort data

dt$lead1order_number <- c(dt$order_number[-1], NA)

# COMMENT OUT NEXT LINE AND RUN, no error with brackets, but one with ifelse
dt$lead1group_name <- c(dt$group_name[-1], NA) 

# done two different ways below
    # if group_name doesn't match lead1group_name, then lead1order_number NA
dt$lead1order_number[dt$group_name != dt$lead1group_name] <- NA  

dt$lead1order_number <- ifelse(dt$group_name != dt$lead1group_name, NA, dt$lead1order_number)

Aucun commentaire:

Enregistrer un commentaire