Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

r - how to drop columns by passing variable name with dplyr?

I have a df as follows:

a <- data_frame(keep=c("hello", "world"),drop = c("nice", "work"))
a
Source: local data frame [2 x 2]
   keep  drop
  (chr) (chr)
1 hello  nice
2 world  work

I can use a %>% select(-drop) to drop the column without problem. however, if I want to pass a variable to present drop column, then it returns error.

name <- "drop"
a  %>% select(-(name))

Error in -(name) : invalid argument to unary operator

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use one_of to find the column positions and then use - to drop it, select(-one_of(name)), if you check ?select, the usage is documented in the Drop variable section in the Examples:

name <- "drop"
a %>% select(-one_of(name))

# A tibble: 2 × 1
#   keep
#  <chr>
#1 hello
#2 world

Or with select_, you need to paste - with the column names to drop them and pass the pasted column names to the .dots parameter if there are more than one column to be dropped:

name <- "drop"
a %>% select_(.dots = paste("-", name))

# A tibble: 2 × 1
#   keep
#  <chr>
#1 hello
#2 world

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...