I have a data frame A and a vector b.
I want to eliminate any columns in A with indices that are in b by doing A[,-b]
Sometimes vector b has length 0. In this case I would like the whole of data frame A to be returned. Instead I get this error:
data frame with 0 columns and 1259 rows
How can I make sure this doesn't happen in this case?
CodePudding user response:
Any reason a control statement won't work? Most of the time there's no need to over-complicate things. It also makes it simple for other people who may need to read or edit your code.
ret_a = function(A, b) {
if (length(b) == 0) {
A
} else {
A[,-b]
}
}
CodePudding user response:
You could use setdiff():
A[, setdiff(1:ncol(A), b)]
This method can handle
b <- NAb <- NULLb <- integer(0)
and returns the entire data A.
