Sometimes, the scripts you created gives you a big surprise due to some sutble differences of the command. Here are two common difficult to catch traps in R programming.
df <- data.frame(a = runif(5), d = runif(5), animals = c('dog','cat','snake','lion','rat'), z = 1:5)
results1 <- df[, -which(names(df) %in% c("a","d"))] # works as expected
# how about this one
results2 <- df[, -which(names(df) %in% c("b","c"))] # surprise! All data are gone
df <- data.frame(a = runif(5), d = runif(5), animals = c('dog','cat','snake','lion','rat'), z = 1:5)
results1 <- df[, !names(df) %in% c("a","d")] # works as expected
# how about this one
results2 <- df[, !names(df) %in% c("b","c")] # returns the un-altered data.frame
dropVec <- c('a','d')
df[dropVec] <- list(NULL)
Look at the following examples, you would expect it to print 1:9, right? Instead, it is print i-1.
n <- 10
for (i in 1:n-1) {
print(i)
}
## [1] 0
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
n <- 10
for (i in 1:(n-1)){
print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9