Say I have this data frame:
df <- data.frame(foo = runif(10), bar = runif(10), boo = runif(10))
# bar boo foo
# 1 0.9561519 0.2152603 0.90986454
# 2 0.9971676 0.8101082 0.78158207
# 3 0.6211555 0.9281131 0.59828786
# 4 0.2332080 0.6063427 0.88131253
# 5 0.6572534 0.3698642 0.61227246
# 6 0.6940809 0.1464231 0.30366349
# 7 0.3924425 0.3706134 0.05930352
# 8 0.7918689 0.8808447 0.90571744
# 9 0.2553619 0.9632559 0.52549238
# 10 0.3772701 0.7657140 0.05102249
I can use starts_with
and ends_with
together when selecting a column like this:
df %>%
select(intersect(starts_with("b"), ends_with("oo")))
As expected, this gives the following:
# boo
# 1 0.2152603
# 2 0.8101082
# 3 0.9281131
# 4 0.6063427
# 5 0.3698642
# 6 0.1464231
# 7 0.3706134
# 8 0.8808447
# 9 0.9632559
# 10 0.7657140
I can also select columns that don't end in oo
by negating ends_with
, like this:
df %>%
select(-ends_with("oo"))
# bar
# 1 0.9561519
# 2 0.9971676
# 3 0.6211555
# 4 0.2332080
# 5 0.6572534
# 6 0.6940809
# 7 0.3924425
# 8 0.7918689
# 9 0.2553619
# 10 0.3772701
Now, I want to combine these behaviours. That is, I want a column that does not end with oo
and starts with b
. So, in my example I should just get the column bar
– but I don't.
df %>%
select(intersect(starts_with("b"), -ends_with("oo")))
# data frame with 0 columns and 10 rows
Above, I show that the intersect
approach works and that the negation of ends_with
also works, but combining these doesn't give the result I expect. Can someone enlighten me as to where I'm going wrong?
Edit : Actually, now that I rerun this in a fresh session I get,
Error in UseMethod("select_") : no applicable method for 'select_' applied to an object of class "function"
Use setdiff
:
df %>%
select(setdiff(starts_with("b"), ends_with("oo")))
# bar
# 1 0.5248344
# 2 0.8835366
# 3 0.3486265
# 4 0.6382468
# 5 0.7378287
# 6 0.2878244
# 7 0.1927559
# 8 0.9787019
# 9 0.5393251
# 10 0.9229542
The negative notation is magic understood by select
, it's not understood by intersect
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.