I have a data frame where I am trying to subset the columns. Incase if I give "undefined columns", it should be display the output
datf <- data.frame(a = c(1,2,3), b = c(4,3,4), c = c(7,6,5))
datf[c('a','b', 'v')]
Error in `[.data.frame`(datf, c("a", "b", "v")) :
undefined columns selected
Expected output
datf[c('a','b', 'v')]
a b
1 1 4
2 2 3
3 3 4
So basically, if there defined columns then fine, or else it should exclude the undefined column and execute the code? Is this possible?
CodePudding user response:
As @zx8754 also suggested in the comments, you can use intersect
like this:
cols <- c('a','b', 'v')
output <- datf[intersect(names(datf), cols)]
output
Output:
a b
1 1 4
2 2 3
3 3 4